Answers for "mongodb delete duplicate documents"

2

mongodb delete duplicate documents

var duplicates = [];
db.collectionName.aggregate([
  { $match: { 
    name: { "$ne": '' }  // discard selection criteria
  }},
  { $group: { 
    _id: { name: "$name"}, // can be grouped on multiple properties 
    dups: { "$addToSet": "$_id" }, 
    count: { "$sum": 1 } 
  }}, 
  { $match: { 
    count: { "$gt": 1 }    // Duplicates considered as count greater than one
  }}
],
{allowDiskUse: true}       // For faster processing if set is larger
)               // You can display result until this and check duplicates 
.forEach(function(doc) {
    doc.dups.shift();      // First element skipped for deleting
    doc.dups.forEach( function(dupId){ 
        duplicates.push(dupId);   // Getting all duplicate ids
        }
    )    
})
// If you want to Check all "_id" which you are deleting else print statement not needed
printjson(duplicates);     
// Remove all duplicates in one go    
db.collectionName.remove({_id:{$in:duplicates}})
Posted by: Guest on April-20-2020

Code answers related to "mongodb delete duplicate documents"

Code answers related to "Javascript"

Browse Popular Code Answers by Language