源地址:https://zackku.com/mongodb-unwind/
在aggregate中,常常會遇到一些字段屬性是數組對象,然后又需要對這些數組對象進行統計。
這時候就需要用到$unwind操作符。這是一個常用的,又容易被忽略的一個操作。
定義
-
field 版
{ $unwind: <field path> } -
document版
{ $unwind: { path: <field path>, includeArrayIndex: <string>, preserveNullAndEmptyArrays: <boolean> } }
- \ 你要打散的字段
- includeArrayIndex,分配一個存該數組索引的字段
- preserveNullAndEmptyArrays,是否輸出空內容。
場景
一個用戶表user,其中一個字段是一個數組對象,存的是用戶的獎勵信息。
這時需要統計用戶A所有獎勵類型為b的總額。
{
user_id:A_id ,
bonus:[
{ type:a ,amount:1000 },
{ type:b ,amount:2000 },
{ type:b ,amount:3000 }
]
}
unwind操作:
db.user.aggregate([
{$unwind:bonus}
])
//結果
{user_id : A_id , bonus:{type : a ,amount : 1000}}
{user_id : A_id , bonus:{type : b ,amount : 2000}}
{user_id : A_id , bonus:{type : b ,amount : 3000}}
統計:
db.user.aggregate([
{$match: {user_id : A_id} },
{$unwind:bonus},
{$match: {'bonus.type' : b} },
{$group: {_id : '$user_id' , amount : {$sum : {'$bonus.amount'}} }}
])
//結果
{_id:A_id , amount : 5000}
參考 :
https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/ $unwind MongoDB
