1.$match 數據過濾類似於mysql中的 where 及 having 對文檔數據狀態進行狀態過濾(100, -100) 關鍵字($match)
db.getCollection('account').aggregate([
{"$match":{"state":{"$in":[100, -100]}}}, {"$group": {"_id": "$gid"}}
])
2.mongo $group 分組後顯示【多個字段】 關鍵字($group)
db.getCollection('account').aggregate([
{"$group":{"_id":{"name": "$name","gid":"$gid","value":"$value"}}}
])
3.聚合文檔中 所有gid的總合 關鍵字($group,$sum)
db.getCollection('account').aggregate([
{"$group":{"_id":null,"gid":{"$sum":"$gid"}}}
])
計算 文檔中去重後的gid 出現次數
db.getCollection('account').aggregate([
{"$group":{"_id": "$gid", "count": {"$sum": 1}}}
])
4.獲取文檔中gid的平均值關鍵字($group,$avg)
db.getCollection('account').aggregate([
{"$group":{"_id":null,"gid":{"$avg":"$gid"}}}
])
5 獲取 文檔中 gid最大最小值 把平均值$avg 替換$max或$min
6. mongo 關聯查詢 (親測有效)
db.getCollection('app_key').aggregate([
{"$lookup": {
"from": "app",
"localField": "app_id",
"foreignField": "_id",
"as": "datas"
}
}
])
1. from: "要連接的表",
2. localField: "當前Collection中需要連接的字段",
3. foreignField: "外連Collection中連接查詢的字段",
4. as: "把獲取到的的值賦值給這個字段
7. 先按gid分組,分完組之後將name屬性映射到數組中
db.getCollection('account').aggregate([
{"$group": {"_id": "$gid", "name_list": {"$push": "$name"}}}
])
8. 按gid 分組, $push把所有重複gid的name 放入name_list中, $sum:1,計算gid重複次數,$sum": "$gid",計算gid重複的總數
$unwind 把每文檔中每條數據中name_list中拆分成單條文檔, 條件字段保留
db.getCollection('account').aggregate([
{"$group":{"_id": "$gid", "name_list": {"$push": "$name"}, "count": {"$sum": 1}, "total": {"$sum": "$gid"}}},
{"$unwind": "$name_list"}
])
如果以上不滿足 訪問這裏
https://blog.csdn.net/zhanjianshinian/article/details/84632745
未完待續!