【发布时间】:2017-06-29 11:56:23
【问题描述】:
我的收藏中有以下文档:
{
_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({ "$group": { "_id": null, "total": { "$sum": { "$sum": { "$map": { "input": "$activities", "as": "a", "in": { "$size": "$$a.travel" } } } } } }})一样简单。这是因为$sum可以直接与数组一起使用,也可以作为 MongoDB 3.2 以来的累加器。根据您自己删除的答案,您此时的 MongoDB 版本似乎比那要旧得多。
标签: mongodb mongodb-query aggregation-framework nosql