爲了有條件地對$group
管道步驟中的匹配進行求和,您需要使用$cond
operator。
測試數據設置:
db.people.insert([
{name:"George", grade:5, school:"MathHighSchool"},
{name:"John", grade:4, school:"MathHighSchool"},
{name:"Paul", grade:3, school:"MathHighSchool"},
{name:"Ringo", grade:5, school:"MathHighSchool"},
{name:"Johnny", grade:2, school:"MathHighSchool"},
{name:"Joshua", grade:7, school:"MathHighSchool"},
])
假設你只想計數,這裏有一個例子聚合(與MongoDB的2.4.8測試):
db.people.aggregate(
{ $match: {
school : 'MathHighSchool'
}},
{ $group: {
_id: "$school",
// Add up matches less than grade 3
low: { $sum: { $cond: [ {$lt: ["$grade", 3] }, 1, 0] }},
// Add up matches between 3 and 5 (inclusive)
medium: { $sum: { $cond:[
{ $and: [ {$gte: ["$grade", 3]}, {$lte: ["$grade", 5]} ] }, 1, 0]
}},
// Add up matches greater than grade 5
high: { $sum: { $cond: [ {$gt: ["$grade", 5] }, 1, 0] }},
}}
)
結果:
{
"result" : [
{
"_id" : "MathHighSchool",
"low" : 1,
"medium" : 4,
"high" : 1
}
],
"ok" : 1
}
[你做了什麼研究?](https://www.google.de/search?q=mongodb+group) – Philipp
你是什麼意思?我一直在嘗試2個小時左右。 – user3108836
{$ group:{_ id:「$ grade」,low:{$ lt:3},medium:{$ and:[{lte:5},{gte:3}],high:{gt:5}} }})像這樣的東西,但does not; t工作 – user3108836