Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete all documents except one in MongoDB

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Assuming that your _id are uniques you can do:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading