How to remove all documents from a collection except a single document in MongoDB?



To remove all documents from a collection except a single document in MongoDB, use remove() based on some condition. Let us create a collection with documents. Following is the query

>db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Larry","StudentAge":21}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c9c9de42d66697741252478") } >db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Mike","StudentAge":21,"StudentCountryName":"US"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c9c9dea2d66697741252479") } >db.removeAllDocumentsExceptOneDemo.insertOne({"StudentName":"Chris","StudentAge":24,"StudentCountryName":"AUS"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c9c9def2d6669774125247a") }

Following is the query to display all documents from a collection with the help of find() method

> db.removeAllDocumentsExceptOneDemo.find().pretty();

This will produce the following output

{    "_id" : ObjectId("5c9c9de42d66697741252478"),    "StudentName" : "Larry",    "StudentAge" : 21 } {    "_id" : ObjectId("5c9c9dea2d66697741252479"),    "StudentName" : "Mike",    "StudentAge" : 21,    "StudentCountryName" : "US" } {    "_id" : ObjectId("5c9c9def2d6669774125247a"),    "StudentName" : "Chris",    "StudentAge" : 24,    "StudentCountryName" : "AUS" }

Following is the query to remove all documents from a collection except a single document i.e. with StudentAge 24

> db.removeAllDocumentsExceptOneDemo.remove({ StudentAge: { $ne: 24 } } ); WriteResult({ "nRemoved" : 2 })

Let us check all the documents now. Following is the query

> db.removeAllDocumentsExceptOneDemo.find().pretty();

Following is the output displaying only a single document

{    "_id" : ObjectId("5c9c9def2d6669774125247a"),    "StudentName" : "Chris",    "StudentAge" : 24,    "StudentCountryName" : "AUS" }
Updated on: 2019-07-30T22:30:25+05:30

797 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements