 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }Advertisements
 