MongoDB聚合管道 [英] MongoDB aggregation pipeline
问题描述
我有这种类型的文件:
collection:People
{name:"George", grade:5, school:"MathHighSchool"}
以及更多示例.
我需要一个查询来查找所有符合以下条件的人:
在MathHighSchool中学习(所以我们有db.people.aggregate({$match:{school:"MathHighSchool"}},....
)
and many more examples.
I need a query that finds all people who:
study in the MathHighSchool (so we have db.people.aggregate({$match:{school:"MathHighSchool"}},....
)
,然后按年级对他们进行分组,因为它显示了年级< 3的人数 3-5岁之间的人数 和年级> 5的人数.有什么想法吗?
and then group them by their grades, as it shows the number of people with grade <3 number of people with grade between 3 and 5 and number of people with grade > 5. Any ideas?
推荐答案
为了在$group
管道步骤中有条件地对匹配进行求和,您需要使用
In order to conditionally sum matches in your $group
pipeline step, you need to use the $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中进行了测试):
Assuming you just want the counts, here is an example aggregation (tested with 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
}
这篇关于MongoDB聚合管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!