Skip to main content

CRUD Operations

In MongoDB, CRUD Operations refer to the basic operations to manage data in your database. CRUD stands for Create, Read, Update, and Delete. These are the fundamental operations that every MongoDB beginner needs to understand and master. This tutorial will guide you through each of these operations, providing clear examples and explanations to aid your learning.

What are CRUD Operations?

CRUD Operations are the basic data manipulation operations in any database system. They include:

  1. Create: This operation allows you to insert new data into your MongoDB database.
  2. Read: This operation allows you to retrieve data from your MongoDB database.
  3. Update: This operation allows you to modify existing data in your MongoDB database.
  4. Delete: This operation allows you to remove data from your MongoDB database.

Create Operations

In MongoDB, you can use the insertOne() or insertMany() method to create or insert data into a collection.

Here is a basic example of using insertOne():

db.collection('students').insertOne({
name: 'John Doe',
age: 20,
subjects: ['Math', 'Physics']
})

And here's how you can use insertMany() to insert multiple documents at once:

db.collection('students').insertMany([
{
name: 'Jane Doe',
age: 22,
subjects: ['English', 'History']
},
{
name: 'Sam Smith',
age: 21,
subjects: ['Chemistry', 'Biology']
}
])

Read Operations

In MongoDB, you can use the find() method to read or retrieve data from a collection.

Here is an example:

db.collection('students').find({name: 'John Doe'})

The find() method returns all matches. If you want to limit your search to one document, you can use the findOne() method:

db.collection('students').findOne({name: 'John Doe'})

Update Operations

In MongoDB, you can use the updateOne() or updateMany() method to update data in a collection.

Here is an example of updateOne():

db.collection('students').updateOne(
{name: 'John Doe'},
{$set: {age: 21}}
)

And here's how you can use updateMany() to update multiple documents at once:

db.collection('students').updateMany(
{age: {$lt: 22}},
{$set: {graduate: true}}
)

Delete Operations

In MongoDB, you can use the deleteOne() or deleteMany() method to delete data from a collection.

Here is an example of deleteOne():

db.collection('students').deleteOne({name: 'John Doe'})

And here's how you can use deleteMany() to delete multiple documents at once:

db.collection('students').deleteMany({age: {$lt: 20}})

In conclusion, mastering CRUD operations is crucial for data manipulation in MongoDB. Practice these operations and try different scenarios to get a good grasp of how to use them effectively. Remember, the key to mastering MongoDB is practice and consistency. Happy learning!