Find duplicate records in MongoDB

前端 未结 4 1939
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 02:14

How would I find duplicate fields in a mongo collection.

I\'d like to check if any of the \"name\" fields are duplicates.

{
    \"name\" : \"ksqn291\         


        
4条回答
  •  情话喂你
    2020-11-28 02:46

    db.getCollection('orders').aggregate([  
        {$group: { 
                _id: {name: "$name"},
                uniqueIds: {$addToSet: "$_id"},
                count: {$sum: 1}
            } 
        },
        {$match: { 
            count: {"$gt": 1}
            }
        }
    ])
    

    First Group Query the group according to the fields.

    Then we check the unique Id and count it, If count is greater then 1 then the field is duplicate in the entire collection so that thing is to be handle by $match query.

提交回复
热议问题