AnnouncementIntroducing MongoDB 8.0, the fastest MongoDB ever! Read more >>

MongoDB CRUD Operations

Table of contents


Basic definition of CRUD operation

Most of the transactional interactions that a user has with a digital platform, like a website or web application, include requests for four basic operations:

  • Creating something new (for example, a customer profile).
  • Reading (like fetching order details for a user).
  • Updating information (like a user’s mobile number or email address).
  • Deleting (for instance, a work phone number).

CRUD is data-oriented, and it's standardized according to HTTP action verbs. The front end of an application captures the information and sends it as an HTTP request to the middleware, which calls the appropriate database functions to complete the task. These four basic functions are collectively called CRUD, the acronym for create, read, update, and delete.

HTTP and corresponding database CRUD operations

Examples of basic operations

CRUD methods are the primary ways you will manage the data in your databases. Whether it is a bulk operation or individual, CRUD operations are essential to every application.

Some examples of a create operation are creating a new user profile in the database, creating a shopping cart for the user, and creating a new book catalog (bulk insert).

Some examples of read operations are fetching product details for a particular search criteria by the user, like when a user searches for a mobile phone of brand “apple”; displaying all the models of the iPhone; displaying a user's product cart information; and viewing employee details on the portal.

Examples of update operations include updating a user’s personal information, cart information, billing address, timestamp, or the serial number of a certain range of products (bulk update).

A few examples of delete operations are deleting products from a user’s cart, deleting a book from favorites, and deleting all the records older than a certain time period (bulk delete).

Let us further explore the definition of CRUD and examine how to execute MongoDB CRUD operations using the MongoDB Query Language (MQL).

What is CRUD in MongoDB?

CRUD operations describe the conventions of a user interface that let users view, search, and modify parts of the database. MongoDB provides an elegant way of performing CRUD operations with the programming language of your choice through its drivers.

MongoDB documents are modified by connecting to a server, querying the proper documents, and then changing the setting properties before sending the data back to the database to be updated.

When it comes to the individual CRUD operations:

  • The create operation is used to insert new documents in the MongoDB database.
  • The read operation is used to query a document in the database.
  • The update operation is used to modify existing documents in the database.
  • The delete operation is used to remove documents from the database.

How to perform CRUD operations

Now that we've defined MongoDB CRUD operations, we can take a look at how to carry out the individual operations and manipulate documents in a MongoDB database. Let's go into the processes of creating, reading, updating, and deleting documents, looking at each operation in turn.

MongoDB methods for CRUD operations

Create operation

For MongoDB CRUD, if the specified collection doesn't exist, the create operation will create the collection when it's executed. Create operations in MongoDB target a single collection, not multiple collections. Insert operations in MongoDB are atomic on a single document level.

MongoDB provides two different create operations that you can use to insert documents into a collection:

insertOne()

As the name indicates, insertOne() allows you to insert one document into the collection. For this example, we’re going to work with a collection called RecordsDB. We can insert a single entry into our collection by calling the insertOne() method on RecordsDB. We then provide the information we want to insert in the form of key-value pairs, establishing the schema.

db.RecordsDB.insertOne({
    name: "Marsh",
    age: "6 years",
    species: "Dog",
    ownerAddress: "380 W. Fir Ave",
    chipped: true
})

If the create operation is successful, a new document is created. The function will return an object where “acknowledged” is “true” and “insertID” is the newly created “ObjectId.”

> db.RecordsDB.insertOne({
... name: "Marsh",
... age: "6 years",
... species: "Dog",
... ownerAddress: "380 W. Fir Ave",
... chipped: true
... })
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5fd989674e6b9ceb8665c57d")
}

insertMany()

It's possible to insert multiple items at one time by calling the insertMany() method on the desired collection. In this case, we pass multiple items into our chosen collection (RecordsDB) and separate them by commas. Within the parentheses, we use brackets to indicate that we are passing in a list of multiple entries. This is commonly referred to as a nested method.

db.RecordsDB.insertMany([{
    name: "Marsh",
    age: "6 years",
    species: "Dog",
    ownerAddress: "380 W. Fir Ave",
    chipped: true},
      {name: "Kitana", 
      age: "4 years", 
      species: "Cat", 
      ownerAddress: "521 E. Cortland", 
      chipped: true}])

db.RecordsDB.insertMany([{ name: "Marsh", age: "6 years", species: "Dog", 
ownerAddress: "380 W. Fir Ave", chipped: true}, {name: "Kitana", age: "4 years", 
species: "Cat", ownerAddress: "521 E. Cortland", chipped: true}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5fd98ea9ce6e8850d88270b4"),
                ObjectId("5fd98ea9ce6e8850d88270b5")
        ]
}

Read operations

The read operations allow you to supply special query filters and criteria that let you specify which documents you want. The MongoDB documentation contains more information on the available query filters. Query modifiers may also be used to change how many results are returned.

MongoDB has two methods of reading documents from a collection:


find()

To get all the documents from a collection, we can simply use the find() method on our chosen collection. Executing just the find() method with no arguments will return all records currently in the collection.

db.RecordsDB.find()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat", "ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "6 years", "species" : "Dog", "ownerAddress" : "380 W. Fir Ave", "chipped" : true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "3 years", "species" : "Dog", "ownerAddress" : "380 W. Fir Ave", "chipped" : true }
{ "_id" : ObjectId("5fd994efce6e8850d88270ba"), "name" : "Kevin", "age" : "8 years", "species" : "Dog", "ownerAddress" : "900 W. Wood Way", "chipped" : true }

In the result, we can see all the records present in the collection. Note that every record has an assigned “ObjectId” mapped to the “_id” key.

If you want to get more specific with a read operation and find a desired subsection of the records, you can use the previously mentioned filtering criteria to choose what results should be returned. One of the most common ways of filtering the results is to search by value.

db.RecordsDB.find({"species":"Cat"})
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat", "ownerAddress" : "521 E. Cortland", "chipped" : true }

findOne()

To get one document that satisfies the search criteria, we can simply use the findOne() method on our chosen collection. If multiple documents satisfy the query, this method returns the first document according to the natural order which reflects the order of documents on the disk. If no documents satisfy the search criteria, the function returns null. The function takes the following form of syntax.

db.{collection}.findOne({query}, {projection})

Let's take the following collection — say, RecordsDB, as an example.

{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "8 years", "species" : "Cat", "ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "6 years", "species" : "Dog", "ownerAddress" : "380 W. Fir Ave", "chipped" : true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "3 years", "species" : "Dog", "ownerAddress" : "380 W. Fir Ave", "chipped" : true }
{ "_id" : ObjectId("5fd994efce6e8850d88270ba"), "name" : "Kevin", "age" : "8 years", "species" : "Dog", "ownerAddress" : "900 W. Wood Way", "chipped" : true }

And, we run the following line of code:

db.RecordsDB.find({"age":"8 years"})

We would get the following result:

{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "8 years", "species" : "Cat", "ownerAddress" : "521 E. Cortland", "chipped" : true }

Notice that even though two documents meet the search criteria, only the first document that matches the search condition is returned.

Update operations

Like create operations, update operations operate on a single collection, and they are atomic at a single document level. An update operation takes filters and criteria to select the documents you want to update.

You should be careful when updating documents, as updates are permanent and can’t be rolled back. This applies to delete operations as well.

For MongoDB CRUD, there are three different methods of updating documents:


updateOne()

We can update a currently existing record and change a single document with an update operation. To do this, we use the updateOne() method on a chosen collection, which here is “RecordsDB.” To update a document, we provide the method with two arguments: an update filter and an update action.

The update filter defines which items we want to update, and the update action defines how to update those items. We first pass in the update filter. Then, we use the “$set” key and provide the fields we want to update as a value. This method will update the first record that matches the provided filter.

db.RecordsDB.updateOne({name: "Marsh"}, {$set:{ownerAddress: "451 W. Coffee St. A204"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "6 years", "species" : "Dog", "ownerAddress" : "451 W. Coffee St. A204", "chipped" : true }

updateMany()

updateMany() allows us to update multiple items by passing in a list of items, just as we did when inserting multiple items. This update operation uses the same syntax for updating a single document.

db.RecordsDB.updateMany({species:"Dog"}, {$set: {age: "5"}})
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }
> db.RecordsDB.find()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat", "ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "5", "species" : "Dog", "ownerAddress" : "451 W. Coffee St. A204", "chipped" : true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "5", "species" : "Dog", "ownerAddress" : "380 W. Fir Ave", "chipped" : true }
{ "_id" : ObjectId("5fd994efce6e8850d88270ba"), "name" : "Kevin", "age" : "5", "species" : "Dog", "ownerAddress" : "900 W. Wood Way", "chipped" : true }

replaceOne()

The replaceOne() method replaces a single document in the specified collection. replaceOne() replaces the entire document, meaning fields in the old document not contained in the new one will be lost.

db.RecordsDB.replaceOne({name: "Kevin"}, {name: "Maki"})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.RecordsDB.find()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat", "ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "5", "species" : "Dog", "ownerAddress" : "451 W. Coffee St. A204", "chipped" : true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "5", "species" : "Dog", "ownerAddress" : "380 W. Fir Ave", "chipped" : true }
{ "_id" : ObjectId("5fd994efce6e8850d88270ba"), "name" : "Maki" }

Delete operations

Delete operations operate on a single collection, like update and create operations. Delete operations are also atomic for a single document. You can provide delete operations with filters and criteria to specify which documents you would like to delete from a collection. The filter options rely on the same syntax that read operations utilize.

MongoDB has two different methods of deleting records from a collection:

deleteOne()

deleteOne() removes a document from a specified collection on the MongoDB server. A filter criteria is used to specify the item to delete. It deletes the first record that matches the provided filter.

db.RecordsDB.deleteOne({name:"Maki"})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.RecordsDB.find()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat", "ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "5", "species" : "Dog", "ownerAddress" : "451 W. Coffee St. A204", "chipped" : true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "5", "species" : "Dog", "ownerAddress" : "380 W. Fir Ave", "chipped" : true }

deleteMany()

deleteMany() is a method used to delete multiple documents from a desired collection with a single delete operation. A list is passed into the method and the individual items are defined with filter criteria as in deleteOne().

db.RecordsDB.deleteMany({species:"Dog"})
{ "acknowledged" : true, "deletedCount" : 2 }
> db.RecordsDB.find()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4 years", "species" : "Cat", "ownerAddress" : "521 E. Cortland", "chipped" : true }

CRUD performance in relational vs non-relational

NoSQL databases are better optimized for create and read operations and offer more scalability. Thus, they’re well suited for higher loads (handle more CRUD operations). They are also flexible in terms of storing information.

In a detailed experiment conducted by ResearchGate on CRUD operations conducted with different types of NoSQL and SQL databases, it was concluded that NoSQL databases performed significantly better than SQL databases in all the CRUD operations, particularly when the number of operations was high. For example, MongoDB excelled in fetching data (read operations), with a mean performance time of 43.5 ms for 100,000 read (find/select) operations. MongoDB also has an advantage in providing atomic updates (field level updates), which is more time-consuming in any other document-oriented database.

Summary

This article covered basic information about CRUD with some examples of how CRUD operations are done in MongoDB. MongoDB Atlas provides a simple way to perform CRUD operations using the UI. You can check out the MongoDB manual to learn more core MongoDB CRUD concepts to develop highly performant, scalable applications.

FAQs

What are the principles of CRUD?

The acronym CRUD stands for the four basic operations that every application should be able to perform, i.e., create, read, update, and delete operations. This means that an application should be able to insert data into the database, read data from the database, update database details, and delete data from the database as needed.

What is a CRUD app?

A crud app relies on crud operations for all the transactions and operations. It has a user interface (front end), a controller or API, and a database that handles the CRUD operations.

What are CRUD operations?

CRUD operations are the basic functions that every application needs to perform to exchange data with a web user — for example, creating a new user profile (CREATE), fetching product details from a database (READ), updating employee information on the employee portal (UPDATE), and removing a particular product from a catalog (DELETE).

What is CRUD?

CRUD is an acronym used for the basic set of operations that every application must be able to perform. It stands for create, read, update, and delete.

Ready to get started?

Launch a new cluster or migrate to MongoDB Atlas with zero downtime.