【发布时间】:2020-11-25 06:45:41
【问题描述】:
我有一个 MongoDB 集合,其中包含以下格式的记录:
[
{ "item1": { "a": 1 }, "item2": { "a": 2 } },
{ "item1": { "a": 3 }, "item3": { "a": 4 } },
{ "item1": { "a": 5 }, "item2": { "a": 6 } },
]
我想获得具有item1、item2 和item3 字段的记录计数(它们不需要是动态的。我只有一组有限的项目)。我需要的是计数以下列方式存在的字段的记录:
{ "item1": 3, "item2": 2, "item3": 1 }
为了获得item1 的计数,我这样做:
db.collection.find({ "item1": { $exists: true }}).count()
有没有一种简单的方法可以在单个查询中汇总所有三个项目的计数?
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework aggregate