How to delete N numbers of documents in mongodb

You can’t set a limit when using remove or findAndModify. So, if you want to precisely limit the number of documents removed, you’ll need to do it in two steps.

db.collectionName.find({}, {_id : 1})
    .limit(100)
    .sort({timestamp:-1})
    .toArray()
    .map(function(doc) { return doc._id; });  // Pull out just the _ids

Then pass the returned _ids to the remove method:

db.collectionName.remove({_id: {$in: removeIdsArray}})

FYI: you cannot remove documents from a capped collection.

Leave a Comment