MongoDB文檔https://mongodb-documentation.readthedocs.io/en/latest/tutorial/aggregation-examples.html#id3
db.inventory.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: … path:'字段名稱’, preserveNullAndEmptyArrays:#防止數據丟失 } }])
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}