Home > front end >  How to delete all documents except one in MongoDB
How to delete all documents except one in MongoDB

Time:10-10

I am building nodejs application and I am using MongoDB official driver(not mongosse)

And I want to write a command to MongoDB.

{"_id": "MAX_ERROR_NODE_SERVERS","what": "conf","serverCount": 10,"added_At": "Sun Oct 09 2022 15:38:36 GMT 0530 (India Standard Time)"}

I have a document like this in MongoDB.

And I want to delete all documents in the collection except the above document.

That means the above document should not be deleted but all other documents should be deleted in the collection

What is the command should I write

CodePudding user response:

Assuming that your _id are uniques you can do:

db.yourNameCollection.deleteMany({
  "_id": {$ne: "MAX_ERROR_NODE_SERVERS"}
})

CodePudding user response:

Query to keep delete all documents except the one whose id = "MAX_ERROR_NODE_SERVERS":

DbCollection.deleteMany({_id: {$ne: "MAX_ERROR_NODE_SERVERS"}})

  • Related