CRUD Operations in MongoDB: Tutorial with Examples

With the continuous evolution of the web, we are now seeing how MongoDB and other document object databases are coming up as alternatives to conventional SQL based databases. There are several advantages that these document object databases have over SQL databases, and the most prominent ones out of all these benefits include scalability and agility.

It is important to note that data in MongoDB is stored binary encoded JSON (BSON) documents format. This format may have a requirement of holding arrays of embedded documents or for that matter values. A document forms a record in MongoDB, which is a structure created out of value and field pairs. 

Let us now discuss create, update, retrieve, and delete operations or CRUD operations in MongoDB. These functions can be broadly classified as data modification functions in MongoDB. These can only be used for a single collection. Insert is a function in MongoDB that can be used to add data to the database.

List of CRUD Operations in MongoDB

1. Creating Documents

How are objects created using MongoDB? MongoDB uses BSON – a binary representation of JSON – for its storage. So, it is quite easy to understand that methods used to perform different operations in the database have something or the other to do with JavaScript. Let us create a user and users’ collection. It is also important to note that tables in SQL are equivalent to collections in MongoDB.{name:”Mike”, job:”doctor”,email:””})
This example uses MongoDB save() for saving the data to the collection.

2. Inserting Documents

  • Batch insert: This function allows for adding a list of documents at the same time to a database. A batch, at a particular point in time, can have hundreds or even thousands of documents. With the capability of inserting multiple documents, this function works a lot faster than other insert functions. A batch insert doesn’t need you to raise individual requests for the hundreds or thousands of documents. It instead works as one Transmission Control Protocol (TCP) request. The time taken during inserts is always significantly less as there is no header processing activity involved. Every document that has to be inserted carries a header that conveys to the database the operation that needs to be performed. Mostly, batch inserts are used to hold sensors data and server logs.
  • Mongoimport: Mongoimport is a command-line tool that is used in place of the batch insert to essential data from MySQL, Oracle, or any other Relational Database Management System (RDBMS). There are times when you may be required to make changes to documents – add a custom ID – before storing it on MongoDB. Another important thing that you should know is that MongoDB only accepts messages as heavy as 16 MB. So, the batch insert puts a restriction on the number of messages it can have. 
  •  Unordered bulk insert: In this function, MongoDB writes operations without following any order. In the event of an error taking place, it will continue with the write operations that are left without any interruption. MongoDB forms a group of the unordered operations while performing them. MongoDB can also seek performance enhancement by reordering listed operations before execution. So, applications don’t have to rely on a sequence when considering this function for bulk insert. Bulk.getOperations() can be used to see how MongoDB groups a set of operations and then executes them. This command can be used to add three documents at the same time but without any order.
  • Ordered bulk insert: In this function, MongoDB follows a sequence when writing operations. An error during any write operation results in MongoDB not performing other write operations. Ordered operations are grouped considering their continuity and type. Adjoining ordered operations belong to the same class are grouped.

For instance, if an ordered list has one insert operation followed by a delete operation followed by two update operations, MongoDB will create three groups to stack these. Group one will consist of one insert operation. The second group will have one delete operation. The third group will put the two update operations together.

The future editions of MongoDB are expected to deal appropriately with this behavior. Each group of ordered bulk lists can’t have more than 1000 operations. In case the number goes beyond that maximum limit, MongoDB creates smaller groups of 1000 operations or less, to adhere to this limit. So if there are 7000 ordered bulk operations, there will be seven groups, each consisting of 1000 bulk operations. To see how grouping and execution are done, first execute the bulk insert command and then use the Bulk.getOperations command. This command can be used to add three documents in order. 

3. Retrieving/reading Documents

Every query in MongoDB is directed at particular documents. MongoDB identifies documents based on the condition defined in a query and then returns those documents to its intended destination. A document retrieval query can have a projection that mentions conditions or criteria that match with the fields of the document that needs to be returned. 

Queries can be modified to put skips, limits and sort orders.

 Let us now discuss how the equality condition is specified. Use the findOne() command to identify a document’s first record. To display results in the proper format, you can use the pretty method. 

Use the db.items.find().pretty() query to identify all the documents listed in a collection and display all of them in a standardized format. You can use an empty query to pick all documents – db.items.find( {} ) – this query has an empty query clause at the end – so it will identify all documents listed in a collection. 

Not specifying the find method with a query document and using an empty query will both deliver the same result. So, db.items.find( {} ) and db.items.find() queries are equivalent in terms of the result they are used for. 

You can manipulate the query and use the query cursor method while the count method lets you find out the number of documents in a collection that match your query. db.items.count()

4. Updating Documents

You need to use the update() method to update documents in MongoDB. The update method features two important elements – query and update. Query parameter comes first followed by the update parameter. Here is an example

db.users.update({name:”Mike”}, {age: 32})

However, this isn’t the right way to update a value pair, which in this case is age. With this, you will overwrite everything in the document. The only thing that will remain in the age. So when we have to update a single value pair in the entire document, we need to use a few keywords. 

db.users.update({name: “Mike”}, { $set: { age: 28}})

This won’t overwrite anything. You would retain all the information the document has. Only the value of age will be updated. 

5. Removing Documents

Use the remove method – – to remove documents from a collection. This command will remove all the documents from the given collection. What it won’t remove are the indexes and the collection itself. At times, the remove command can take a query as a parameter. If you want to remove documents that match the criteria mentioned in the query, use db.items.remove({“item”: “Pen”) command. 

Use the db.items.remove({” item” : “Bag},1) command to remove only one document from a collection. To remove all the documents, collection, and indexes, use the command (drop method).


If you are interested to know more about Big Data, check out our PG Diploma in Software Development Specialization in Big Data program which is designed for working professionals and provides 7+ case studies & projects, covers 14 programming languages & tools, practical hands-on workshops, more than 400 hours of rigorous learning & job placement assistance with top firms.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Want to share this article?

Lead the Data Driven Technological Revolution

400+ Hours of Learning. 14 Languages & Tools. IIIT-B Alumni Status.
Advanced Certificate Programme in Big Data from IIIT Bangalore

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Big Data Course

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks