【问题标题】:How to find duplicate entries in collection using aggregation如何使用聚合查找集合中的重复条目
【发布时间】:2019-08-05 04:53:15
【问题描述】:
{ "_id" : ObjectId("4f127fa55e7242718200002d"), "id":1, "name" : "foo"}
{ "_id" : ObjectId("4f127fa55e7242718200002d"), "id":2, "name" : "bar"}
{ "_id" : ObjectId("4f127fa55e7242718200002d"), "id":3, "name" : "baz"}
{ "_id" : ObjectId("4f127fa55e7242718200002d"), "id":4, "name" : "foo"}
{ "_id" : ObjectId("4f127fa55e7242718200002d"), "id":5, "name" : "bar"}
{ "_id" : ObjectId("4f127fa55e7242718200002d"), "id":6, "name" : "bar"}

我想使用聚合通过“名称”字段查找此集合中的所有重复条目。例如。 "foo" 出现两次,"bar" 出现 3 次。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    您可以按名称和计数分组。然后使用大于 1 的计数进行过滤。

    db.collection.aggregate([
        {
          $group: {
            _id: "$name",
            count: { $sum: 1 }
           }
         },
        {
         $match:{count:{$gt:1}}
         }
       ])
    

    输出:

    { "_id" : "foo", "count":2}
    { "_id" : "bar", "count":3}
    

    【讨论】:

      【解决方案2】:

      您可以在aggrgation 中使用group 舞台

      db.collection.aggregate([{
        $group: {
          _id: "$name",
          count: { $sum: 1 },
          name: { $first: "$name" }
        }
      }])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多