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

mongodb

Solution

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.

Problem

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

Original source