我有一个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()
有没有一种简单的方法来在一个查询中聚合这三个项目的数量?
item5: {}
? - Yedhu Krishnan$match
):https://mongoplayground.net/p/2Y4RD0mgTZd - micklitemGroup
的字段,其值为1、2、3等,那么我能否按itemGroup
每个值的数量统计呢? - Yedhu Krishnan