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

本文详细介绍了MongoDB中的聚合操作,包括求和(sum)、平均(avg)、最大(min)、最小(max)、首次(first)、末次(last)等运算符的使用方法。此外还讲解了如何使用$addToSet和$push将数据加入数组,以及如何通过$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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值