Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete N numbers of documents in mongodb

Tags:

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?

like image 230
Yogesh Avatar asked Sep 28 '13 09:09

Yogesh


People also ask

How do I limit the number of files in MongoDB?

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.

How do I delete all files in MongoDB?

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.

Which command will remove all documents in a collection with field age set to 10?

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.


2 Answers

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.

like image 93
WiredPrairie Avatar answered Sep 22 '22 06:09

WiredPrairie


Let N be number of records to delete.

    db.collectionName.find().limit(N).forEach(doc =>       {         db.collectionName.remove({_id:doc._id})      }     ) 
like image 27
Prashant Sharma Avatar answered Sep 19 '22 06:09

Prashant Sharma