Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove all documents from a collection except one in MongoDB

Tags:

mongodb

Is there any way to remove all the documents except one from a collection based on condition.

I am using MongoDB version 2.4.9

like image 618
AshokGK Avatar asked Jun 04 '14 12:06

AshokGK


People also ask

How do I remove all files from a collection in MongoDB?

To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.

What is the fastest operation to clear an entire collection in MongoDB?

MongoDB's db. collection. drop() is used to drop a collection from the database.

Which MongoDB command is used to remove document from a collection?

MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag. deletion criteria − (Optional) deletion criteria according to documents will be removed.

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.


3 Answers

You can do this in below way,

db.inventory.remove( { type : "food" } )

Above query will remove documents with type equals to "food"

To remove document that not matches condition you can do,

db.inventory.remove( { type : { $ne: "food" } } )

or

db.inventory.remove( { type : { $nin: ["Apple", "Mango"] } } )

Check here for more info.

like image 61
maximus ツ Avatar answered Oct 23 '22 04:10

maximus ツ


To remove all documents except one, we can use the query operator $nin (not in) over a specified array containing the values related to the documents that we want to keep.

db.collections.remove({"field_name":{$nin:["valueX"]}})

The advantage of $nin array is that we can use it to delete all documents except one or two or even many other documents.

To delete all documents except two:

db.collections.remove({"field_name":{$nin:["valueX", "valueY"]}})

To delete all documents except three:

db.collections.remove({"field_name":{$nin:["valueX", "valueY", "valueZ"]}})
like image 39
Taha EL BOUFFI Avatar answered Oct 23 '22 06:10

Taha EL BOUFFI


Query

db.collection.remove({ "fieldName" : { $ne : "value"}})
like image 35
Tushar Mishra Avatar answered Oct 23 '22 04:10

Tushar Mishra