新聞中心
這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)MongoDB中有哪些聚合命令,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
1.聚合管道法:
管道聚合方法可以理解為合計流水線法,就是把集合里若干含數(shù)值型的文檔記錄其鍵對應(yīng)的值進(jìn)行各種分類統(tǒng)計,有點(diǎn)類似于SQL語言里的group by。
語法如下:
db.collection.agrregate(
[$match:{
{$group:{
]
說明:
field1為分類字段;field2為含各種統(tǒng)計操作符的數(shù)值型字段,比如$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為統(tǒng)計結(jié)果字段名,$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.單一目標(biāo)聚合法:
語法:
db.collection.count(query,options)
例如:
> db.test.distinct("id")
[ "001", "002", "003" ]
>
> db.test.find({ok:true}).count()
5
上述就是小編為大家分享的MongoDB中有哪些聚合命令了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道。
網(wǎng)站名稱:MongoDB中有哪些聚合命令-創(chuàng)新互聯(lián)
分享路徑:http://www.ef60e0e.cn/article/ddjjdg.html