我在我的收藏文件喜歡:查詢嵌套數組中元素的總數 - 嵌入文檔的MongoDB
{
_id: 1,
activities: [
{
activity_id: 1,
travel: [
{
point_id: 1,
location: [-76.0,19.1]
},
{
point_id: 2,
location: [-77.0,19.3]
}
]
},
{
activity_id: 2,
travel: [
{
point_id: 3,
location: [-99.3,18.2]
}
]
}
]
},
{
_id: 2,
activities: [
{
activity_id: 3,
travel: [
{
point_id: 4,
location: [-75.0,11.1]
}
]
}
]
}
我能得到的活動總數,如下:
db.mycollection.aggregate(
{$unwind: "$activities"},
{$project: {count:{$add:1}}},
{$group: {_id: null, number: {$sum: "$count" }}}
)
我得到(3個活動):
{ "result" : [ { "_id" : null, "number" : 3 } ], "ok" : 1 }
問題:何我能獲得所有旅行中的元素總數嗎?
預期的結果:4
元件
它們是:
{
point_id: 1,
location: [-76.0,19.1]
},
{
point_id: 2,
location: [-77.0,19.3]
},
{
point_id: 3,
location: [-99.3,18.2]
},
{
point_id: 4,
location: [-75.0,11.1]
}
其實這是和仍然像'db.mycollection.aggregate簡單({「$組「:{」_id「:null,」total「:{」$ sum「:{」$ sum「:{」$ map「:{」input「:」$ activities「,」as「:」a「, 「in」:{「$ size」:「$$ a.travel」}}}}}}})'。這是因爲'$ sum'可以直接用於數組,也可以作爲自MongoDB 3.2以來的累加器。通過您自己刪除的答案,您目前的MongoDB版本似乎比這個要舊得多。 –