【问题标题】:Find all duplicate documents in a MongoDB collection between a date range查找日期范围内 MongoDB 集合中的所有重复文档
【发布时间】:2021-02-24 03:16:40
【问题描述】:

假设我有一个包含一组文档的集合。像这样的。

{ "_id" : ObjectId("4f127fa55e7242718200002d"), "orderId" : "ABCD1234", "createdAt": ISODate("2019-10-10T17:30:00.000Z") }
{ "_id" : ObjectId("4f127fa55e7242718200002e"), "orderId" : "XYZ1234", "createdAt": ISODate("2020-08-10T17:30:00.000Z") }
{ "_id" : ObjectId("4f127fa55e7242718200002f"), "orderId" : "ABCD1234", "createdAt": ISODate("2020-11-10T17:30:00.000Z") }
{ "_id" : ObjectId("4f127fa55e7242718200002a"), "orderId" : "ABCD1234", "createdAt": ISODate("2020-11-10T17:30:00.000Z") }
{ "_id" : ObjectId("4f127fa55e7242718200002b"), "orderId" : "XYZ1234", "createdAt": ISODate("2020-11-10T17:30:00.000Z") }
{ "_id" : ObjectId("4f127fa55e7242718200002c"), "orderId" : "PQRS1234", "createdAt": ISODate("2020-11-10T17:30:00.000Z") }
{ "_id" : ObjectId("4f127fa55e7242718200003d"), "orderId" : "HIJK1234", "createdAt": ISODate("2020-11-10T17:30:00.000Z") }

我想在 2020 年 11 月 1 日之后查找此集合中具有相同 orderId 的所有重复条目。

我无法让聚合查询工作,它可以在日期范围内的一组数据上找到重复记录。

【问题讨论】:

    标签: mongodb duplicates aggregation-framework


    【解决方案1】:

    你可以试试,

    • $match createdAt 日期大于您输入的日期
    • $group by orderId 并从重复中获取第一组的记录,获取重复记录的计数
    • $match 如果 count 大于 1 表示重复记录
    • $replaceRoot 替换根中的根对象
    // correct date if i am wrong
    var date = new Date("2020-11-02T00:00:00.000Z");
    db.collection.aggregate([
      {
        $match: { createdAt: { $gte: date } }
      },
      {
        $group: {
          _id: "$orderId",
          root: { $first: "$$ROOT" },
          count: { $sum: 1 }
        }
      },
      {
        $match: { count: { $gt: 1 } }
      },
      {
        $replaceRoot: { newRoot: "$root" }
      }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 2012-03-18
      • 1970-01-01
      • 2016-04-23
      • 2021-09-18
      相关资源
      最近更新 更多