您的位置:首页 > 数据库 > Mongodb

MongoDB:The Definitive Guide 2nd笔记(二)

2016-09-10 08:50 309 查看
Grouping operators
sum

avg

max min first last

addToSet

push

Grouping behavior

unwind

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
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: