How Do I Delete a Document in Mongodb?

Read it in 9 Mins

Last updated on
20th Sep, 2022
Published
31st Dec, 2021
Views
10,357
How Do I Delete a Document in Mongodb?

MongoDB is the most popular NoSQL database, which stores data as documents. The documents are basically JSON objects and there are many ways to delete them. We can also delete these documents through the GUI of MongoDB Compass or MongoDB Atlas. But in this article, we will learn to delete it through the command-line tool of Mongo shell.   

Prerequisites

We have used Windows 10 in this tutorial. Please make sure you have downloaded the MongoDB Community Server and installed it. It is easy to setup and you need to make sure that you have added it in the Environment variable in your PC.

Four ways

We will next learn about the four ways to delete a MongoDB document through Mongo shell. The four ways are - 

  • The method of db.collection.remove() 
  • The command delete 
  • The method of db.collection.deleteOne() 
  • The method of db.collection.deleteMany() 

Once we have mongo shell installed on our system, we can go to the terminal and type mongo. If everything is ok, we will be logged in to the shell. Also, make sure that you have a locally installed MongoDB running through Compass or mongod command. 

Inside the Mongo shell we can see all the databases using show databases and then switch to the database in which we are going to work, using use <database-name> command

db.collection.remove() method 

With this method, we can delete all the documents, some of the documents, or a single document. We specify a parameter in it and depending on it, the number of documents will be deleted. 

In our employeeDB database, we have a collection named employees. We have 3 records in our employees collection.

We will delete all the employees aged 39, by the command db.employees.remove({ “age”: 39 }) . Here, it deleted only one record, because only one employee matched the criteria.  

We can also limit the delete, to just one record by setting the justOne parameter to true. In this method, we are passing an empty object and deleting the first record.

We have again added the two deleted documents. Now, we can delete all the documents using the command db.employees.remove({}).  

The command: delete

The delete command can also be used to delete documents from a Mongo dB collection. Internally the remove method also uses the delete command. Now, the delete command needed to be run with the db.runCommand() and we need to pass an object to it. Here, the delete key will contain the collection name. And the deletes key will contain an array that will have a query and can also have the limit variable set. 

With the below command, we are deleting an employee who have age of 38, by limiting the count to one. 

db.runCommand( 
   { 
      delete: "employees", 
      deletes:  [ { q: { age: 38 }, limit: 1 } ] 
   } 
) 

So, when we give this command only one record will be deleted. 

db.collection.deleteOne() method

The db.collection.deleteOne() method is similar to the db.collection.remove() method, but with a special clause of deleting one document only. We saw the example of db.collection.remove() method earlier, but it can be used in other configurations also.

But the db.collection.deleteOne() method can be used to delete only one document. We have added some documents in our employees collection.  

Now, in mongo shell run the command db.employees.deleteOne({ "age": 39 }) and it will delete the first employee i.e. Parag.  

Now, the employee Parag is deleted from our collection employees.  

We can also delete the first document of the collection, by not passing any argument. The command is db.employees.deleteOne({}), in our case. It will simply delete the document, which is first in the collection.  

Now, the employee Amit is deleted from the employees collection, because it was at the top of our collection.  

db.collection.deleteMany() method

The db.collection.deleteMany() method is almost similar to that of db.collection.remove() method, but with a special clause of deleting many documents. We need to pass a parameter/filter to it, and it deletes the documents according to it. When all the documents match the filter from a collection, it deletes all the documents. With the db.collection.deleteOne() method we can delete only one document, even if the criteria match for many documents. 

But we don’t have such restrictions in db.collection.deleteMany() method. Infact we can also delete all the document in the collection. We will see example of both next. 

We have added documents again in our employees collection, through MongoDB Compass in our locally installed MongoDB instance. Notice, that we have three employees with age more than 38. 

Now, we want to delete the documents of all employees with age more than 38. For that we will use the command db.employees.deleteMany({ "age": { $gt: 38 } }) and it will delete three employees from our collection.  

Now, when we check the employees collection in MogoDB compass, we can see three employees with age of 39 are deleted from the collection. 

Now, to delete all the documents from the collection we use the command db.employees.deleteMany({}) and it will remove the remining two employees from our employees collection.

Now, our employees collection have no documents.  

Deleting through MongoDB Compass

We can also delete documents, using the awesome free tool of MongoDB Compass.  To install MongoDB compass, simply go to https://www.mongodb.com/ and hover over Products and then in Tools, click Compass. 

In the next page, just click on Download Now button and it will take us to the next page.  

Here, we must click again on MongoDB compass and download a zip file. We simply need to install it after extracting the zip file. 

Once compass is installed, simply open it and click on Connect button and it will connect us to the locally installed MongoDB instance. Notice that we also can give a connection string from a cloud-based MongoDB database, like MongoDB Atlas in it.

We already have several databases created. But when you start MongoDB for the first time, you will only see the admin database. We will go inside a database called employeeDB, by clicking on it.  

Here, we have an employees collection and in it we have four documents. Simply click on the collection.  

It will show us the four documents. Now hover over the document you want to delete and four small buttons will appear. Now, click on the delete icon.  

It will ask for our approval to delete the document. Simply click on the Delete button.  

And the document of employee named Parag will be deleted.  

Atomicity Concerns

Atomicity is part of the ACID properties in database. Now, ACID means Atomicity, Consistency, Isolation, and Durability. All traditional Relational databases like Oracle, MySQL are ACID by nature. Atomicity is the most important property in ACID and it means that, if there are a series of database operations then either everything occurs or nothing occurs. 
 
MongoDB and other NoSQL databases were never designed for ACID properties. MongoDB was specially created with scalability in mind. So, if we have a drop statement, update statement, or a delete statement in MongoDB they are guaranteed to be atomic only at the Single document level. These operations are also called write operations, and they are atomic only at a single document level. 

Now, if our single document contains multiple sub-documents, it is still guaranteed as atomic and if it fails the automatic rollback will occur, like in the relational databases. But, if the write operation concerns multiple documents, it is not guaranteed in MongoDB. 
 
Now, we have seen the db.collection.deleteMany() method earlier with a filter parameter. But it can have two other parameters also. The complete syntax of db.collection.deleteMany() method is as below. 

db.collection.deleteMany( 
   <filter>, 
   { 
      writeConcern: <document>, 
      collation: <document> 
   } 
) 

Here, we can give the writeConcern and the collation also.  The writeConcern is something we are concerned about, because it is related to the write operation and the atomicity.  

writeConcern is an optional parameter, which is in the form of document expressing the write concern to use if greater then majority. Write concern can include the following fields: 

{ w: <value>, j: <boolean>, wtimeout: <number> } 

  • w option is to request acknowledgement, that the write operation has passed to a specified number of mongod instances. 
  • j option is to request acknowledgement, that the write operation had been written to the disk-journal 
  • wtimeout option is to specify the time limit, to prevent the write operations from blocking indefinitely. 

Using the w option, the following <value> are available: 

  • w: 1 – Requests acknowledgement that the write concern has passed to the single mongod instance. It is also the default option. 
  • w: 0 – Requests no acknowledgement of the write operation. 
  • w: “majority” – It requests acknowledgement that the write operation have passed to majority of primary and secondary servers. 

Now, we will look into the j option values. 

  • j: true – It requests acknowledgement that the different mongod instances, mentioned in w: <value>, have written to on-disk journal. 

The wtimeout option specifies the time limit in milliseconds, for the write concern. It causes write operations to return with an error after the specified limit. 

Managing Databases with Delete  

To keep databases clean and manageable, deleting and removing files is an essential task. In this post, we have explored the different ways to delete documents in a MongoDB database. All of these methods work for different purposes and in different scenarios. We first learnt about the four different ways, to delete documents from MongoDB collections through the command line interface of Mongo shell. Then we got to know how to delete documents through the awesome free graphical user interface of MongoDB Compass. 

Lastly, we have learned about the atomicity concerns while deleting documents and especially multiple documents. We have also learned about the option of writeConcern in the db.collection.deleteMany() method. 

Profile

Nabendu Biswas

Author

Nabendu Biswas is a Full Stack JavaScript Developer, who has been working in the IT industry for the past 16 years and has worked for world’s top development firms, and Investment banks. He is a passionate tech blogger. He is also a tech youtuber and loves to teach people JavaScript. He is also an Apress author with three Gatsby books published. 

Develop the skills of the future via outcome-based immersive learning

Speak to our Career Advisor now!

Select
Your Message (Optional)