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?
The Limit() Method To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.
To delete all documents from a collection, pass an empty filter document {} to the db. collection. deleteMany() method. The method returns a document with the status of the operation.
remove() The remove() method removes documents from the database. It can remove one or all documents from the collection that matches the given query expression.
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}) } )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With