【发布时间】:2020-02-03 07:58:02
【问题描述】:
这是我根据fullDate 和key 字段对集合中的文档进行计数的查询:
Collection.aggregate([
{ $match: { $and: [
{ month },
{ year },
{ isBooked },
] }},
{ $group: { _id: "$fullDate", count: { $sum: 1 } } }
]
假设这是过滤集合(在第一阶段之后,即$match):
{ month: 5, year: 2012, isBooked: true, fullDate: 2020/7/5, key: 123qaz }
{ month: 5, year: 2012, isBooked: true, fullDate: 2020/7/5, key: 123qaz }
{ month: 5, year: 2012, isBooked: true, fullDate: 2020/7/5, key: 223qaz }
{ month: 5, year: 2012, isBooked: true, fullDate: 2020/7/5, key: 323qaz }
上述查询将返回2020/7/5: 4。我需要修改查询以获得2020/7/5: 3,因为有两个文档具有相同的123qaz 键。我不想按键计算重复项。
【问题讨论】:
-
如果您将
key: { $addToSet: "$key" }添加到您的选项(即添加到{ $group ...})会怎样?
标签: mongodb mongodb-query aggregation-framework