Find duplicate records in MongoDB

前端 未结 4 1940
伪装坚强ぢ
伪装坚强ぢ 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:51

    The answer anhic gave can be very inefficient if you have a large database and the attribute name is present only in some of the documents.

    To improve efficiency you can add a $match to the aggregation.

    db.collection.aggregate(
        {"$match": {"name" :{ "$ne" : null } } }, 
        {"$group" : {"_id": "$name", "count": { "$sum": 1 } } },
        {"$match": {"count" : {"$gt": 1} } }, 
        {"$project": {"name" : "$_id", "_id" : 0} }
    )
    

提交回复
热议问题