MongoDB分組查詢(xún)和聚合查詢(xún)實(shí)例教程
1、單一字段分組
分組后不會(huì)展示其他字段, _id為固定寫(xiě)法,userid為分組字段
# 比如對(duì)比sql:select userid from testgroup by userid db.test.aggregate({"$group":{"_id":"$userid"}} )
效果:
2、多字段分組
_id為固定寫(xiě)法,userid與articleid為分組字段,多字段時(shí)需要設(shè)置一個(gè)別名
# 比如對(duì)比sql:select userid,articleid from testgroup by userid,articleid db.test.aggregate({"$group":{"_id":{"userid":"$userid","articleid":"$articleid"}}})
效果:
3、條件匹配分組
$match表示匹配條件,在group前表示where,在后表示having,userid為分組字段
# 比如對(duì)比sql:select userid from testwhere userid in("1","2") group by userid db.test.aggregate( {"$match":{"userid":{"$in":["1","2"]}}}, {"$group":{"_id":"$userid"}} ) 或者 # 比如對(duì)比sql:select userid,articleid from test where userid in("1","2") group by userid db.test.aggregate( {"$match":{"userid":{"$in":["1","2"]}}}, {"$group":{"_id":{"userid":"$userid","articleid":"$articleid"}}} ) 或者h(yuǎn)aving聚合查詢(xún) # 比如:select userid,avg(price) as avg from test where userid >'10' group by userid having avg>35 db.test.aggregate( {"$match":{"userid":{"$gt":"10"}}}, {"$group":{"_id":"$userid",'avg':{"$avg":"$price"}}}, {"$match":{"avg":{"$gt":35}}} )
效果:
4、分組分頁(yè)排序
限制:$limit、跳過(guò):$skip
db.test.aggregate( {"$group":{"_id":"$userid"}}, {"$skip":1}, {"$limit":2} )
5、聚合分組
聚合分組,分為:$sum、$avg、$max、$min、$first、$last,聚合結(jié)果需要使用別名,并且可以結(jié)合條件和排序等元素
為了測(cè)試聚合,增加一下文件:
db.test.insert([{ "articleid":"1", "price":200, "userid":"5" },{ "articleid":"2", "price":300, "userid":"5" },{ "articleid":"3", "price":400, "userid":"5" },{ "articleid":"1", "price":200, "userid":"6" },{ "articleid":"2", "price":300, "userid":"7" }]);
5.1、sum聚合-求數(shù)值總和
求某個(gè)數(shù)值總和,userid分組字段[可以用于多字段聚合],{"$sum":$price}表示求price合計(jì)
db.test.aggregate({"$group":{"_id":"$userid","total":{"$sum":"$price"}}})
5.2、sum聚合-求分組后數(shù)量
db.test.aggregate({"$group":{"_id":"$userid","total":{"$sum":1}}})
效果:
5.3、avg、max、min聚合
avg、max、min可以分開(kāi)使用,也可以一起使用
db.test.aggregate({"$group":{"_id":"$userid","avg":{"$avg":"$price"},"max":{"$max":"$price"},"min":{"$min":"$price"}}})
效果:
5.4、復(fù)合聚合
可以多字段聚合求值,通過(guò)sum
與avg、max、min
進(jìn)行組合
db.test.aggregate({"$group":{"_id":"$userid" ,"total":{"$sum":"$price"} ,"avg":{"$avg":"$price"}}})
效果:
5.5、聚合分組排序
對(duì)聚合結(jié)果進(jìn)行排序,$sort-排序,avg-聚合結(jié)果的別名,1:升序,-1:降序
# 先按userid降序,再avg升序 db.test.aggregate({"$group":{"_id":"$userid" ,"avg":{"$avg":"$price"}}} ,{"$sort":{"avg":1}} ,{"$sort":{"_id":-1}})
效果:
5.6、首尾取值聚合
$first-第一個(gè)元素、$last-最后一個(gè)元素
vdb.test.aggregate({"$group":{"_id":"$userid","prices":{"$first":"$price"}}})
效果:
5.7、聚合分組拼接
等同于group_concat,$push-元素可重復(fù),$addToSet-元素不可重復(fù),將分組后的數(shù)據(jù)拼接為一個(gè)數(shù)組
db.test.aggregate({"$group":{"_id":"$userid","names":{"$push":"$price"}}})
效果:
補(bǔ)充:關(guān)于MongoDB中一些復(fù)雜的聚合分組查詢(xún)操作
一、字段切割&條件判斷
匯總各個(gè)店鋪【$shop_name】在某個(gè)時(shí)間段【$patrol_time】?jī)?nèi)違規(guī)【$whether_violates == ‘Y’】的記錄數(shù)
1.$substr:[‘字段名’,開(kāi)始下標(biāo),結(jié)束下標(biāo)]
2.$cond:{if…then…else}
查詢(xún)SQL如下:
db.t_tbshop_patrol.aggregate([ { "$project": { "yearMonthDay": { "$substr": ["$patrol_time", 0, 10] }, "patrol_time": 1, "shop_name": 1, "whether_violates": 1, "y_count": { "$sum": { "$cond": { "if": { "$eq": ["$whether_violates", "Y"] }, "then": 1, "else": 0 } } } } }, { "$match": { "patrol_time": { "$gte": "2021-09-29 00:00:00", "$lte": "2021-09-29 23:59:59" } } }, { "$group": { "_id": { "patrol_time": "$yearMonthDay", "shop_name": "$shop_name" }, "violate_y": { "$sum": "$y_count" } } }, /* 只展示匯總結(jié)果大于0的店鋪數(shù)據(jù),去掉下面{'$match'}則展示所有店鋪數(shù)據(jù) */ { "$match": { "violate_y": { "$gt": 0 } } } ])
查詢(xún)結(jié)果如下:
/* 1 */
{
"_id" : {
"patrol_time" : "2021-09-29",
"shop_name" : "VETA個(gè)護(hù)海外旗艦店"
},
"violate_y" : 5.0
}/* 2 */
{
"_id" : {
"patrol_time" : "2021-09-29",
"shop_name" : "swisseFuJun海外專(zhuān)賣(mài)店"
},
"violate_y" : 24.0
}/* 3 */
{
"_id" : {
"patrol_time" : "2021-09-29",
"shop_name" : "咿兒潤(rùn)旗艦店"
},
"violate_y" : 1.0
}
二、聯(lián)表查詢(xún)&類(lèi)型轉(zhuǎn)換&拆分?jǐn)?shù)組
根據(jù)日期查詢(xún)訂單表中每條訂單數(shù)據(jù)每種商品(非贈(zèng)品)的總金額(業(yè)務(wù)需要顯示倉(cāng)庫(kù),但原始數(shù)據(jù)中只有倉(cāng)庫(kù)編號(hào),所以和倉(cāng)庫(kù)信息表【t_warehouse_info】使用聯(lián)表查詢(xún))
1.$lookup
2.$toDouble、$convert
3.$unwind
原始數(shù)據(jù)示例:
{ "_id" : ObjectId("5f33abcdfc12b1f2d21b2e5d"), /* 訂單編號(hào) */ "order_sn" : "12023232223920", "add_time" : "2021-09-29 20:01:25", "complete_time" : "1596330674", /* 倉(cāng)庫(kù)編號(hào) */ "fhck" : "151", "last_update" : "2021-09-29 09:14:03", "lylx" : "1", /* 訂單商品明細(xì):同一筆訂單下的同一商品可能有多條,所以需要根據(jù)商品編號(hào)【goods_sn】分組求和 */ "orderDetailGets" : [ { "goods_sn" : "6925425422173", "goods_id" : "2518", "goods_number" : "3", "goods_price" : "35.19", "shop_price" : "79.00", "share_price" : "35.19", /* 支付金額 */ "share_payment" : "35.19", "original_order_sn" : "12023232223920", "goods_name" : "口力橡皮糖500g", /* 是否贈(zèng)品(1:是;0:否)*/ "is_gift" : "0", "share_shipping_fee" : "0.00" }, { "goods_sn" : "6971083865227", "goods_id" : "1569", "goods_number" : "1", "goods_price" : "1.87", "shop_price" : "4.50", "share_price" : "1.87", "share_payment" : "1.87", "original_order_sn" : "12023232223920", "goods_name" : "口力組合橡皮糖隨手包30g", "is_gift" : "0", "share_shipping_fee" : "0.00" }, { "goods_sn" : "6971083865227", "goods_id" : "1569", "sku_id" : "1569", "goods_number" : "2", "goods_price" : "1.87", "shop_price" : "4.50", "goods_price" : "1.87", "share_payment" : "3.74", "original_order_sn" : "12023232223920", "goods_name" : "口力組合橡皮糖隨手包30g", "is_gift" : "0", "share_shipping_fee" : "0.00" } ], "order_msg" : "", "order_status" : "5", "pay_time" : "2021-09-29 20:03:13", "payment" : "37.06", "sd_name" : "口力旗艦店", "total_amount" : "84.54", "weigh" : "0.800000" }
查詢(xún)SQL如下:
db.getCollection('t_shop_order').aggregate([ { "$match": { "add_time": { "$gte": "2021-12-14 00:00:00", "$lte": "2021-12-14 23:59:59" } } }, /* $lookup聯(lián)表查詢(xún):相當(dāng)于left join;關(guān)聯(lián)后的子表數(shù)據(jù)無(wú)論是1對(duì)1還是1對(duì)多,都會(huì)形成一個(gè)數(shù)組對(duì)象 */ { "$lookup": { "from": "t_warehouse_info", /* 主表的關(guān)聯(lián)字段名 */ "localField": "fhck", /* 關(guān)聯(lián)表的字段名 */ "foreignField": "ckdm", /* 關(guān)聯(lián)表別名,作為數(shù)據(jù)的字段名 */ "as": "warehouse_info" } }, /* $unwind拆分?jǐn)?shù)組對(duì)象,扁平化展示 */ { "$unwind": "$orderDetailGets" }, { "$project": { "order_sn": 1, "add_time": 1, "goods_sn": "$orderDetailGets.goods_sn", "is_gift": "$orderDetailGets.is_gift", /* $convert類(lèi)型轉(zhuǎn)換:將字符串轉(zhuǎn)換為int類(lèi)型,以助于后面的數(shù)據(jù)統(tǒng)計(jì) */ "goods_number": { "$convert": { "input": "$orderDetailGets.goods_number", "to": "int" } }, "goods_name": "$orderDetailGets.goods_name", /* $ifNull空判斷:如果對(duì)應(yīng)字符串為null,則設(shè)置默認(rèn)值為0 */ /* $toDouble轉(zhuǎn)換為浮點(diǎn)型:將數(shù)據(jù)轉(zhuǎn)換為浮點(diǎn)型數(shù)據(jù) */ "share_payment": { "$ifNull": [{ "$toDouble": "$orderDetailGets.share_payment" }, 0] }, "ckmc": "$warehouse_info.ckmc" } }, { "$match": { "is_gift": "0" } }, { "$unwind": "$ckmc" }, { "$group": { _id: { "order_sn": "$order_sn", "add_time": "$add_time", "goods_sn": "$goods_sn", "goods_name": "$goods_name" }, "goods_number": { "$sum": "$goods_number" }, "share_payment": { "$sum": "$share_payment" } } } ])
查詢(xún)SQL如下:
/* 1 */ { "_id" : { "order_sn" : "12023232223920", "add_time" : "2021-12-14 12:22:16", "goods_sn" : "6925425422173", "goods_name" : "口力橡皮糖500g" }, "goods_number" : 3, "share_payment" : 35.19 } /* 2 */ { "_id" : { "order_sn" : "12023232223920", "add_time" : "2021-12-14 22:37:09", "goods_sn" : "6971083865227", "goods_name" : "口力組合橡皮糖隨手包30g" }, "goods_number" : 3, "share_payment" : 5.61 }
總結(jié)
到此這篇關(guān)于MongoDB分組查詢(xún)和聚合查詢(xún)的文章就介紹到這了,更多相關(guān)MongoDB分組查詢(xún)和聚合查詢(xún)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mongodb常見(jiàn)操作符和運(yùn)算符總結(jié)
MongoDB 提供了豐富的操作符(Operators)和運(yùn)算符(Expressions)用于在查詢(xún)和更新文檔時(shí)指定條件和操作數(shù)據(jù),本文將通過(guò)代碼示例給大家詳細(xì)的總結(jié)一下Mongodb常見(jiàn)操作符和運(yùn)算符,需要的朋友可以參考下2024-01-01SpringBoot整合MongoDB的實(shí)現(xiàn)步驟
MongoDB 是一個(gè)介于關(guān)系數(shù)據(jù)庫(kù)和非關(guān)系數(shù)據(jù)庫(kù)之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫(kù)當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫(kù)的。本文介紹SpringBoot項(xiàng)目如何整合MongoDB2021-06-06mongodb使用docker搭建replicaSet集群與變更監(jiān)聽(tīng)(最新推薦)
replicaSet和cluster從部署難度相比,replicaSet要簡(jiǎn)單許多。如果所存儲(chǔ)的數(shù)據(jù)量規(guī)模不算太大的情況下,那么使用replicaSet方式部署mongodb是一個(gè)不錯(cuò)的選擇,這篇文章主要介紹了mongodb使用docker搭建replicaSet集群與變更監(jiān)聽(tīng),需要的朋友可以參考下2023-03-03Mongodb中MapReduce實(shí)現(xiàn)數(shù)據(jù)聚合方法詳解
Mongodb是針對(duì)大數(shù)據(jù)量環(huán)境下誕生的用于保存大數(shù)據(jù)量的非關(guān)系型數(shù)據(jù)庫(kù),針對(duì)大量的數(shù)據(jù)。接下來(lái)通過(guò)本文給大家介紹Mongodb中MapReduce實(shí)現(xiàn)數(shù)據(jù)聚合方法詳解,感興趣的朋友一起學(xué)習(xí)吧2016-05-05基于MongoDB數(shù)據(jù)庫(kù)的數(shù)據(jù)類(lèi)型和$type操作符詳解
下面小編就為大家?guī)?lái)一篇基于MongoDB數(shù)據(jù)庫(kù)的數(shù)據(jù)類(lèi)型和$type操作符詳解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07