【问题标题】:Count unique documents in MongoDB计算 MongoDB 中的唯一文档
【发布时间】:2020-02-03 07:58:02
【问题描述】:

这是我根据fullDatekey 字段对集合中的文档进行计数的查询:

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


【解决方案1】:

试试这个:

Collection.aggregate([{
    $match: {
        $and: [
            { month },
            { year },
            { isBooked },
        ]
    }
},
/** group by fullDate & push unique keys to an array */
{ $group: { _id: "$fullDate", uniqueKeys: { $addToSet: '$key' } } },
/** project a new field 'count' which is size of uniqueKeys, _id is projected by default,
 *  Use $addFields in place of project if multiple fields to be projected */
{ $project: { count: { $size: '$uniqueKeys' } } }])

测试: MongoDB-Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    相关资源
    最近更新 更多