Published on

Understanding CRUD Operations in MongoDB

Authors
  • avatar
    Name
    Hieu Cao
    Twitter

Introduction

CRUD stands for Create, Read, Update, and Delete—the four basic operations you can perform on a database. MongoDB, as a NoSQL database, provides intuitive methods to handle these operations. In this blog, we'll explore each of these operations with practical examples using MongoDB query commands.


Prerequisites

Before we dive in, ensure you have:

  • MongoDB installed and running.
  • Access to the MongoDB shell or terminal.
  • A basic understanding of MongoDB documents and collections.

Switching and Creating Databases in MongoDB

Switch to a Database

To switch to a database, use the use command. If the database does not exist, MongoDB will create it as soon as you insert data into it.

Example:

> use myDatabase

This command switches to (or creates) the database named myDatabase.

Verify Current Database

To check which database you are currently using:

> db

Create a Database

In MongoDB, databases are created implicitly. Simply switch to a new database and perform an operation like inserting a document:

> use newDatabase
> db.users.insertOne({ name: "Example User" });

The newDatabase will be created with a users collection once the first document is inserted.


1. Create Operation

The create operation allows you to insert new documents into a collection. Use the insertOne or insertMany commands in the MongoDB shell.

Example:

Single Document Insertion:

> db.users.insertOne({
  name: "John Doe",
  email: "john.doe@example.com",
  age: 30,
  isActive: true
});

Multiple Documents Insertion:

> db.users.insertMany([
  { name: "Alice", email: "alice@example.com", age: 25, isActive: true },
  { name: "Bob", email: "bob@example.com", age: 28, isActive: false }
]);

2. Read Operation

The read operation retrieves documents from a collection. Use the find command to fetch data.

Example:

Retrieve All Documents:

> db.users.find();

Retrieve Specific Documents:

> db.users.find({ isActive: true });

Retrieve with Projection:

> db.users.find({ isActive: true }, { name: 1, email: 1 });

3. Update Operation

The update operation modifies existing documents in a collection. MongoDB provides the updateOne and updateMany commands.

Example:

Update a Single Document:

> db.users.updateOne(
  { name: "John Doe" },
  { $set: { age: 31 } }
);

Update Multiple Documents:

> db.users.updateMany(
  { isActive: false },
  { $set: { isActive: true } }
);

4. Delete Operation

The delete operation removes documents from a collection. Use the deleteOne or deleteMany commands.

Example:

Delete a Single Document:

> db.users.deleteOne({ name: "Bob" });

Delete Multiple Documents:

> db.users.deleteMany({ isActive: false });

Tips and Best Practices

  1. Backup Your Data: Always back up your data before performing delete operations.
  2. Use Filters Wisely: Be specific with your filters to avoid unintended changes or deletions.
  3. Indexing: Leverage indexing to improve the performance of read and update operations.
  4. Test in Development: Test your queries in a development environment before running them in production.

Conclusion

Understanding CRUD operations is fundamental when working with MongoDB. With the examples provided, you should now be able to perform basic database operations confidently. In the next post, we’ll cover MongoDB aggregation and advanced queries.

Happy coding!