如何使用聚合在集合中查找重复条目


夏花
2025-03-17 01:51:57 (22天前)


{“ id”:ObjectId(“4f127fa55e7242718200002d”),“id”:1,“name”:“foo”}
{“
id”:ObjectId(“4f127fa55e7242718200002d”),“id”:2,“name”:“bar”}
{“_ id”:ObjectId(“4f127fa55e7242718200002d”),“id”:3,“……

3 条回复
  1. 0# 北极星微控 | 2019-08-31 10-32



    您可以使用



    阶段性的

    aggrgation




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

    2. </code>

  2. 1# 与之 | 2019-08-31 10-32




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





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

    2. </code>



    输出:
    </强>




    1. { _id : foo”, count”:2}
      { _id : bar”, count”:3}

    2. </code>

登录 后才能参与评论