Grouping operators
$sum
"$sum" : value
//计算每个文档的value的总和,value也可以是更加复杂的表达式
> db.sales.aggregate(
{
"$group" : {
"_id" : "$country",
"totalRevenue" : {"$sum" : "$revenue"}
}
})
$avg
"$avg" : value
//计算value的均值
> db.sales.aggregate(
{
"$group" : {
"_id" : "$country",
"totalRevenue" : {"$average" : "$revenue"},
"numSales" : {"$sum" : 1}
}
})
max min first last
"$max" : expr
"$min" : expr
"$first" : expr
"$last" : expr
“ max"and" min” look through each document and find the extreme values.
$max和$min搜索每一个文档找到最大值和最小值
db.scores.aggregate(
{
"$group" : {
"_id" : "$grade",
"lowestScore" : {"$min" : "$score"},
"highestScore" : {"$max" : "$score"}
}
})
Alternatively, “ first"and" last” return useful results when your data is sorted by the fields you are looking for.
如果数据是已经排序好了,就用$first和$last,比使用$min和$max更加有效。如果数据并没有排序或没有打算排序,使用$min和$max更加有效
$addToSet
"$addToSet" : expr
把当前遇到的数据添加到数组中,如果expr不在数组中,就添加进去。
在结果数组中每个value只出现一次。
$push
"$push" : expr
把当前遇到的值都加到数组中,返回一个数组包含所有值。
Grouping behavior
$group must collect all documents, split them into groups, then send them to the next operator in the pipeline.
This means that, with sharding, $group will first be run on each shard and then the individual shards’ groups will be sent to the mongos to do the final grouping and the remainder of the pipeline will be run on the mongos (not the shards).
$unwind
Unwinding 把数组中的每一个元素分到单独的文档中,举例如下:
//每条博客可能有多个评论
db.blog.findOne()
{
"_id" : ObjectId("50eeffc4c82a5271290530be"),
"author" : "k",
"post" : "Hello, world!",
"comments" : [
{
"author" : "mark",
"date" : ISODate("2013-01-10T17:52:04.148Z"),
"text" : "Nice post"
},
{
"author" : "bill",
"date" : ISODate("2013-01-10T17:52:04.148Z"),
"text" : "I agree"
}
]
}
利用unwind可以得到
db.blog.aggregate({"$unwind" : "$comments"})
{
"results" :
{
"_id" : ObjectId("50eeffc4c82a5271290530be"),
"author" : "k",
"post" : "Hello, world!",
"comments" : {
"author" : "mark",
"date" : ISODate("2013-01-10T17:52:04.148Z"),
"text" : "Nice post"
}
},
{
"_id" : ObjectId("50eeffc4c82a5271290530be"),
"author" : "k",
"post" : "Hello, world!",
"comments" : {
"author" : "bill",
"date" : ISODate("2013-01-10T17:52:04.148Z"),
"text" : "I agree"
}
}
],
"ok" : 1
}
本文详细介绍了MongoDB中的聚合操作,包括求和(sum)、平均(avg)、最大(min)、最小(max)、首次(first)、末次(last)等运算符的使用方法。此外还讲解了如何使用$addToSet和$push将数据加入数组,以及如何通过$unwind来展开数组字段。
183

被折叠的 条评论
为什么被折叠?



