CRUD Operations in MongoDB

Aniket Mitra 05 Feb, 2024 • 6 min read

Introduction

This guide will introduce you to CRUD operations, the backbone of data manipulation. You’ll learn how to Create, Read, Update, and Delete data, with real-world examples and step-by-step explanations.

SQL Databases includes the flexibility of schema-design, relaxation of its ACID properties and its distributed data storage capability thus performing better for storage of large-scale unstructured data.

There are different types of NoSQL databases; MongoDB falls under Document-based databases.

different types of NoSQL databases

It’s called NoSQL because it is different from SQL databases in properties. The detailed difference and other salient features of MongoDB are given in my previous blog. I highly recommend reading that blog of mine first then coming here. The storage structure of MongoDB can be represented using the below hierarchical structure.

MongoDB Data Storage Model

So a database contains single or multiple collections, each containing one or many documents. Collection can be thought of similar to Tables in RDBMS AND Documents as each record/tuple/row. This article was published as a part of the Data Science Blogathon.

What is CRUD in MongoDB?

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations that can be performed on data in a database.

CRUD MongoDB

CRUD Operation in MongoDB

In MongoDB, CRUD operations are performed slightly differently compared to traditional SQL databases. Here’s how:

Create: In MongoDB, you can create a new document using the insertOne() or insertMany() methods.

Read: You can read or retrieve documents from a MongoDB database using the find() method.

Update: Updating documents in MongoDB can be done using the updateOne(), updateMany(), or replaceOne() methods.

Delete: You can delete documents using the deleteOne() or deleteMany() methods.

Remember, MongoDB is a NoSQL database, so it doesn’t require a predefined schema like SQL databases do. This means you can store documents that have different sets of fields in the same collection, which can be very powerful and flexible.

How to Perform Create Operation?

A “Create” operation refers to the process of adding new data to your database. In MongoDB, this is done using the insertOne() or insertMany() methods.

insertOne()

The insertOne() method is used to insert a new document into a collection. Here’s an example:

db.collection('students').insertOne({

    name: 'Aniket',

    age: 21,

    major: 'Computer Science'

});

In this example, a new document is being created in the ‘students’ collection. The document contains three fields: ‘name’, ‘age’, and ‘major’.

insertMany()

The insertMany() method is used to insert multiple documents into a collection at once. Here’s an example:

db.collection('students').insertMany([

    {

        name: 'Aniket',

        age: 21,

        major: 'Computer Science'

    },

    {

        name: 'Jane Doe',

        age: 22,

        major: 'Mathematics'

    }

]);

In this example, two new documents are being created in the ‘students’ collection.

Real-World Example

Imagine you’re building a system for a university. You need to store information about students, such as their name, age, and major. Each time a new student enrolls, you would use a “Create” operation to add their information to your database.

Here’s how you might do it:

db.collection('students').insertOne({

    name: 'New Student',

    age: 18,

    major: 'Undeclared'

});

This would add a new document to the ‘students’ collection with the name ‘New Student’, age 18, and an ‘Undeclared’ major.

Sure, let’s delve into the concept of “Read Operations” in MongoDB.

How to Perform Read Operation?

A “Read” operation refers to the process of retrieving or viewing data from your database. In MongoDB, this is done using the find() and findOne() methods.

find()

The find() method is used to retrieve multiple documents from a collection. Here’s an example:

db.collection('students').find({ major: 'Computer Science' });

In this example, the find() method retrieves all documents in the ‘students’ collection where the ‘major’ field is ‘Computer Science’.

findOne()

The findOne() method is used to retrieve a single document from a collection. Here’s an example:

db.collection('students').findOne({ name: 'Aniket' });

In this example, the findOne() method retrieves the first document it finds in the ‘students’ collection where the ‘name’ field is ‘Aniket’.

Real-World Example

Imagine you’re building a system for a university. You need to retrieve information about students, such as their name, age, and major. Each time a student logs in, you would use a “Read” operation to retrieve their information from your database.

Here’s how you might do it:

let student = db.collection('students').findOne({ name: 'Logged In Student' });

console.log(student);

This would retrieve and print the document of the logged-in student from the ‘students’ collection.

Sure, let’s break down the concept of “Update Operations” in MongoDB.

How to Perform Update Operation?

An “Update” operation refers to the process of modifying existing data in your database. In MongoDB, this is done using the updateOne(), updateMany(), and replaceOne() methods.

updateOne()

The updateOne() method is used to update the first document that matches the query. Here’s an example:

db.collection('students').updateOne(

    { name: 'Aniket' }, 

    { $set: { major: 'Mathematics' } }

);

In this example, the updateOne() method updates the ‘major’ field of the first document in the ‘students’ collection where the ‘name’ field is ‘Aniket’.

updateMany()

The updateMany() method is used to update all documents that match the query. Here’s an example:

db.collection('students').updateMany(

    { major: 'Undeclared' }, 

    { $set: { major: 'General Studies' } }

);

In this example, the updateMany() method updates the ‘major’ field of all documents in the ‘students’ collection where the ‘major’ field is ‘Undeclared’.

replaceOne()

The replaceOne() method is used to replace the first document that matches the query with a new document. Here’s an example:

db.collection('students').replaceOne(

    { name: 'Aniket' }, 

    { name: 'Aniket', age: 22, major: 'Mathematics' }

);

In this example, the replaceOne() method replaces the first document in the ‘students’ collection where the ‘name’ field is ‘Aniket’ with a new document.

Real-World Example

Imagine you’re building a system for a university. You need to update information about students, such as their name, age, and major. Each time a student changes their major, you would use an “Update” operation to modify their information in your database.

Here’s how you might do it:

db.collection('students').updateOne(

    { name: 'Changing Student' }, 

    { $set: { major: 'New Major' } }

);

This would update the ‘major’ field of the document of the changing student in the ‘students’ collection.

Sure, let’s break down the concept of “Delete Operations” in MongoDB.

What is a Delete Operation?

A “Delete” operation refers to the process of removing existing data from your database. In MongoDB, this is done using the deleteOne() and deleteMany() methods.

deleteOne()

The deleteOne() method is used to delete the first document that matches the query. Here’s an example:

db.collection('students').deleteOne({ name: 'Aniket' });

In this example, the deleteOne() method deletes the first document in the ‘students’ collection where the ‘name’ field is ‘Aniket’.

deleteMany()

The deleteMany() method is used to delete all documents that match the query. Here’s an example:

db.collection('students').deleteMany({ major: 'Undeclared' });

In this example, the deleteMany() method deletes all documents in the ‘students’ collection where the ‘major’ field is ‘Undeclared’.

Real-World Example

Imagine you’re building a system for a university. You need to delete information about students, such as when they graduate or leave the university. Each time a student leaves, you would use a “Delete” operation to remove their information from your database.

Here’s how you might do it:

db.collection('students').deleteOne({ name: 'Graduating Student' });

This would delete the document of the graduating student from the ‘students’ collection.

Conclusion

CRUD operations form the backbone of any database system, and MongoDB is no exception. Understanding how to Create, Read, Update, and Delete data in MongoDB is crucial for managing and manipulating your data effectively.

  • The Create operation allows you to add new data to your database.
  • The Read operation enables you to retrieve data from the database.
  • The Update operation lets you modify existing data.
  • The Delete operation removes data from the database.

Each operation has its own methods and use-cases, and understanding them is key to leveraging the full power of MongoDB. Remember, practice is essential when learning new concepts, so try out these operations for yourself!

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Aniket Mitra 05 Feb 2024

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear