您好,登录后才能下订单哦!
这期内容当中小编将会给大家带来有关MongoDB中有哪些聚合命令,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
1.聚合管道法:
管道聚合方法可以理解为合计流水线法,就是把集合里若干含数值型的文档记录其键对应的值进行各种分类统计,有点类似于SQL语言里的group by。
语法如下:
db.collection.agrregate(
[$match:{<field>}},
{$group:{<field1>,<field2>}}
]
说明:
field1为分类字段;field2为含各种统计操作符的数值型字段,比如$sum, $avg, $min,$max等操作符
>use test
> db.test.insert(
... [{id:"001",amount:2,price:15.2,ok:true},
... {id:"001",amount:3,price:14.8,ok:true},
... {id:"002",amount:4,price:40,ok:true},
... {id:"002",amount:2,price:10,ok:true},
... {id:"003",amount:3,price:20.3,ok:true}
... ]
... )
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 5,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.test.aggregate({ $match:{ok:true}})
{ "_id" : ObjectId("5b50388dff7043cec86841af"), "id" : "001", "amount" : 2, "price" : 15.2, "ok" : true }
{ "_id" : ObjectId("5b50388dff7043cec86841b0"), "id" : "001", "amount" : 3, "price" : 14.8, "ok" : true }
{ "_id" : ObjectId("5b50388dff7043cec86841b1"), "id" : "002", "amount" : 4, "price" : 40, "ok" : true }
{ "_id" : ObjectId("5b50388dff7043cec86841b2"), "id" : "002", "amount" : 2, "price" : 10, "ok" : true }
{ "_id" : ObjectId("5b50388dff7043cec86841b3"), "id" : "003", "amount" : 3, "price" : 20.3, "ok" : true }
> db.test.aggregate(
... {
... $group:{
... _id:'$id',
... total:{$sum:"$amount"}
... }
... })
{ "_id" : "003", "total" : 6 }
{ "_id" : "002", "total" : 12 }
{ "_id" : "001", "total" : 10 }
>
说明:_id:'$id',id为分类字段名,total为统计结果字段名,$sum为求和操作符号 ,$amount为求和字段。
2.map-reduce法:
> var chenfeng=db.test.mapReduce(
... function(){
... emit(this.id,this.amount)
... },
... function(key,values){
... return Array.sum(values)
... },
... {query:{ok:true},out:{replace:"result"}}
... )
> db[chenfeng.result].find()
{ "_id" : "001", "value" : 5 }
{ "_id" : "002", "value" : 6 }
{ "_id" : "003", "value" : 3 }
>
3.单一目标聚合法:
语法:
db.collection.count(query,options)
例如:
> db.test.distinct("id")
[ "001", "002", "003" ]
>
> db.test.find({ok:true}).count()
5
上述就是小编为大家分享的MongoDB中有哪些聚合命令了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。