1
votes

Schema - Database: yelp_camp, Collection: campgrounds, Number of records in the collection is equaled to Four

ISSUE - Duplicate records exist in the collection, wish to delete all except the first one.

The database collection snapshot, { "_id" : ObjectId("5cc9729f48ec2b0add99866e"), "name" : "CampAliBaba101234", "image" : "https://photosforclass.com/download/flickr-2770447094", "__v" : 0 } { "_id" : ObjectId("5cc974b46e587f0b00855b0d"), "name" : "CampAliBaba101234", "image" : "https://photosforclass.com/download/flickr-2770447094", "__v" : 0 } { "_id" : ObjectId("5cc9facd11f218081b57f8f0"), "name" : "CampAliBaba101234", "image" : "https://photosforclass.com/download/flickr-2770447094", "__v" : 0 } { "_id" : ObjectId("5cca658c5ecabc0a7ff79e4e"), "name" : "CampAliBaba101234", "image" : "https://photosforclass.com/download/flickr-2770447094", "__v" : 0 } Tried using the below-mentioned code but in vain,

Tried below mentioned mongo query in shell, db.campgrounds.ensureIndex({"name":1}, {unique:"true", dropDups:"true"})

Expected - The duplicate records should be deleted and only one unique record should exist.

Actual - The following error is returned, { "ok" : 0, "errmsg" : "E11000 duplicate key error collection: yelp_camp.campgrounds index: image_1 dup key: { : \"https://photosforclass.com/download/flickr-2770447094\" }", "code" : 11000, "codeName" : "DuplicateKey" }

1

1 Answers

0
votes

Just try with this

db.getCollection('Test').find({  
   "name":"CampAliBaba101234"
}).forEach((data)=>{  
   var i = 0; 
      db.getCollection('Test').find(   {  
      "name":"CampAliBaba101234"
   }   ).forEach((doc)=>   {  
      if (i>0)   db.getCollection('Test').remove(      {  
         _id:data._id
      }      ) 
        i++
   }   )
});