Table of contents
1.
Introduction
2.
CRUD Operations
2.1.
Create Operation
2.2.
Read Operation
2.3.
Update Operation
2.4.
Delete Operation
2.5.
Points to Remember:
3.
Frequently Asked Questions
4.
Key Takeaways
Last Updated: Mar 27, 2024

CRUD Operations in MongoDB | Part 3

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

MongoDB is document-oriented, no sequel(No SQL) database. It was released in August 2009. MongoDB replaces the concept of rows of conventional relational data models with something known as documents.

 

MongoDB offers developers the flexibility to work with evolving data models. Since it is document-based, it allows embedded documents, arrays and represents complex hierarchical relationships using a single record.

 

It is also schema-free, which means that the keys defined in the document are not fixed. As a result, massive data migration can be ruled out. 

 

You must be wondering, when we already have SQL, why does NoSQL or MongoDB come into the picture?

There are various reasons why MongoDB is widely used. To learn more, visit our Introduction to MongoDB article.

CRUD Operations

CRUD stands for Create, Read, Update and Delete. These are the basic operations of any database. So, let's see how to perform these operations in MongoDB.

Create Operation

As we already know, MongoDB stores data as a BSON document that is a binary representation of JSON. A create operation in MongoDB will insert a new document into the collection. 

 

If the collection into which the document is to be inserted does not exist, insert operation will create it.

 

The following are the two primary ways to add documents to a collection.

 

  1. insertOne()

This function will insert one document at a time into the collection. The syntax is as follows:

 

Syntax:

db.collection.insertOne(

   <document>,

   {

      writeConcern: <document>

   }

)

 

Here, the parameter document refers to the data to insert into the collection.

 

2. insertMany()

This function will insert multiple documents at a time into the collection. The syntax is as follows:

 

Syntax:

db.collection.insertMany(

   [ <document 1> , <document 2>, ... ],

   {

      writeConcern: <document>,

      ordered: <boolean>

   }

)

 

Here, the parameter document refers to an array of documents to insert into the collection. By default, documents are inserted in order.

Read Operation

When retrieving documents from a collection, the read operation is used. It's similar to searching through a set of documents. 

 

To read documents from a collection, MongoDB provides the following methods:

 

  1. db.collection.find()

This operation selects documents from a collection or view and returns a cursor to the selected documents. The syntax is as follows:

 

Syntax:

db.collection.find(query, projection)

 

  • The projection parameter determines which fields are returned in the matching documents. 

 

  • The projection parameter takes a document of the following form:

{ <field1>: <value>, <field2>: <value> ... }

Update Operation

The update operation is used to make changes to documents that already exist in a collection. Update operations in MongoDB are limited to a single collection. 

 

We can set criteria, or filters, to identify the documents that need to be updated. The syntax is the same for the read operation.
 

To update documents in a collection, MongoDB provides the following methods:
 

  1. db.collection.updateOne()

This method updates a single document within the collection based on the filter. The syntax of this function is given below:

 

Syntax:

db.collection.updateOne(

   <filter>,

   <update>,

   {

     upsert: <boolean>,

     writeConcern: <document>,

     collation: <document>,

     arrayFilters: [ <filterdocument1>, ... ],

     hint:  <document|string>    // Available starting in MongoDB 4.2.1

   }

)

 

  • There are two possible values for the argument upsert. If it is set to true, it creates a new document if no documents match the filter. Or it updates a single document that matches the filter. When set to false, it does not create a new document if there is no match.
  • The parameter update contains update operator expressions, i.e. the modifications we need to make.

 

2. db.collection.updateMany()

This function updates all documents that match the specified filter for a collection. The syntax of this function is given below:

 

Syntax:

db.collection.updateMany(

   <filter>,

   <update>,

   {

     upsert: <boolean>,

     writeConcern: <document>,

     collation: <document>,

     arrayFilters: [ <filterdocument1>, ... ],

     hint:  <document|string>  // Available starting in MongoDB 4.2.1

   }

)

 

3. db.collection.replaceOne()

This method replaces a single document within the collection based on the filter. The syntax of this function is given below:

 

Syntax:

db.collection.replaceOne(

   <filter>,

   <replacement>,

   {

     upsert: <boolean>,

     writeConcern: <document>,

     collation: <document>,

     hint: <document|string>       // Available starting in 4.2.1

   }

)

 

  • The parameter replacement contains the replacement document.

Delete Operation

Documents are removed from a collection using delete operations. Delete operations in MongoDB are limited to a single collection. 

 

We can set criteria, or filters, to indicate which documents should be deleted. The read operations use the same syntax as these filters.
 

To delete documents from a collection, MongoDB provides the following methods:


1. db.collection.deleteOne()

This method deletes a single document from a collection. The syntax of this function is given below:
 

Syntax:

db.collection.deleteOne(

   <filter>,

   {

      writeConcern: <document>,

      collation: <document>,

      hint: <document|string>     // Available starting in MongoDB 4.4

   }

)

 

2. db.collection.deleteMany()

It deletes all the documents that match the filter from a collection. The syntax of this function is given below:

 

Syntax:

db.collection.deleteMany(

   <filter>,

   {

      writeConcern: <document>,

      collation: <document>

   }

)

Points to Remember:

@) In the above CRUD operations, the parameter: 

 

  • writeConcern is optional. It can be referred to as the level of acknowledgement requested from MongoDB for write operations. To learn more about it, you can see the official documentation.
  • Collation is optional. Using Collation, users can set language-specific string comparison criteria, such as rules for lettercase and accent marks. To learn more about it, you can see the official documentation.
  • The filter specifies deletion criteria using query operators.

 

@) All CRUD operations in MongoDB are limited to a single collection. On the level of a single document, all these operations in MongoDB are atomic.

Frequently Asked Questions

 

What are the primary CRUD operations of MongoDB?

Answer: In MongoDB, we can create, read, update, and delete documents.

 

What is the maximum document size in MongoDB?

Answer: The maximum size of a BSON document is 16 megabytes. The maximum document size helps to guarantee that a single document does not consume too much RAM or bandwidth during transmission.

 

Can we store PDF files in MongoDB?

Answer: Yes, we can store PDF files in MongoDBby using GridFs. We can also and extract texts from a PDF file by using some features.

 

How does MongoDB store binary data?

Answer: MongoDB uses the BSON binary type to store any binary data. 

 

Can MongoDB store blobs?

Answer: No, MongoDB cannot store blobs.

Key Takeaways

In this article, you were introduced to MongoDB, its functional features, and features that make it the most popular non-relational database. 

 

This article is a part of three blog series on MongoDB. The second part of this blog contains tutorials to help you create Databases, Collections and Documents in MongoDB. And the third blog contains CRUD operations in MongoDB. 

 

For a complete understanding of MongoDB, we suggest you read all three articles.

 

Happy Learning!

Live masterclass