How to delete N numbers of documents in mongodb
In my collections, documents contains key like status and timestamp. When I want to find latest ten documents then I write following query
db.collectionsname.find().sort({"timestamp"-1}).limit(10)
This query gives me results which I want but when I want to delete latest ten documents then I was writing the following query
db.collectionsname.remove({"status":0},10).sort({"timestamp":-1})
but it shows following error
TypeError: Cannot call method 'sort' of undefined
and again I wrote the same query as below
db.collectionsname.remove({"status":0},10)
It deletes only one document. So how can I write a query which deletes ten latest documents and sorts on timestamp?
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 _id
s to the remove method:
db.collectionName.remove({_id: {$in: removeIdsArray}})
FYI: you cannot remove documents from a capped collection.
Let N be number of records to delete.
db.collectionName.find().limit(N).forEach(doc =>
{
db.collectionName.remove({_id:doc._id})
}
)
You can pipeline the output of find query mapping to use _id
and performing a remove based on $in
query such as:
db.collection.remove({_id:
{ $in: db.collection.find().sort({timestamp:-1}).limit(100).map(a => a._id) }
})
To remove N number of documents in your collection myCollection
:
db.getCollection('myCollection').find({}).limit(N).forEach(function(doc){
db.getCollection('myCollection').remove({_id: doc._id});
})