MongoDB Dropping records where group is by count

I have a lot of records containing duplicate addresses. Basically, I want to delete those records that have more than 50 duplicate addresses but less than 300.

This is how I can get those records that I want to delete:

db.directories.aggregate( [
   { $group: { _id: { address: "$address" }, total: { $sum: 1 } } },
   { $match: { total: { $gt: 50, $lt: 300 } } },
   { $sort: { total: -1 } }
], { allowDiskUse: true });

      

+3


source to share


1 answer


You can use the cursor method to iterate over the cursor returned from and delete documents using as in the following example: forEach()

aggregate()

remove()



var pipeline = [
   { $group: { _id: { address: "$address" }, total: { $sum: 1 } } },
   { $match: { total: { $gt: 50, $lt: 300 } } },
   { $sort: { total: -1 } }
];
var options = { allowDiskUse: true };
db.directories.aggregate(pipeline, options).forEach(function (doc){
    var query = {"address": doc._id.address};
    db.directories.remove(query);
});

      

+2


source







All Articles