How to remove duplicates based on a key in Mongodb?

后端 未结 8 820
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 20:56

I have a collection in MongoDB where there are around (~3 million records). My sample record would look like,

 { \"_id\" = ObjectId(\"50731xxxxxxxxxxxxxxxxxx         


        
8条回答
  •  自闭症患者
    2020-11-30 21:16

    This is the easiest query I used on my MongoDB 3.2

    db.myCollection.find({}, {myCustomKey:1}).sort({_id:1}).forEach(function(doc){
        db.myCollection.remove({_id:{$gt:doc._id}, myCustomKey:doc.myCustomKey});
    })
    

    Index your customKey before running this to increase speed

提交回复
热议问题