MongoDB Basics: CRUD Operations

When working with MongoDB, the core operations you'll frequently perform are often referred to as CRUD: Create, Read, Update, and Delete. These operations allow you to manipulate the data stored in your MongoDB database and are fundamental to managing your application’s data lifecycle. Let’s dive right into each of these CRUD operations with practical examples to enhance your understanding.

Create Operation

The Create operation allows you to add new documents to a collection in MongoDB. A document is a basic unit of data in MongoDB, represented in BSON (Binary JSON) format. You can create a document using the insertOne() or insertMany() methods, depending on whether you want to add a single document or multiple documents at once.

Example of InsertOne

Here’s how to create a new document in a collection called users:

db.users.insertOne({
  name: "Alice",
  age: 30,
  email: "alice@example.com"
});

In this example, we're adding a document for a user named Alice, complete with her age and email. After executing this command, MongoDB returns an acknowledgment that includes the ID of the newly created document.

Example of InsertMany

If you want to add multiple users at once, you can use insertMany():

db.users.insertMany([
  { name: "Bob", age: 25, email: "bob@example.com" },
  { name: "Charlie", age: 28, email: "charlie@example.com" }
]);

In this instance, two new documents (for Bob and Charlie) are added simultaneously. Batch insertion can significantly improve performance when adding large volumes of data.

Read Operation

The Read operation is used to retrieve documents from a collection. MongoDB provides various methods to read documents, but the most commonly used are find() and findOne().

Example of Find

You can retrieve all documents from a collection like this:

db.users.find({});

This command will return all user documents. However, in a real-world scenario, you often want to filter the results.

Example of Filtering

To find specific users, you can pass a query to the find() method. For example, if you want to find users who are aged 30 and above:

db.users.find({ age: { $gte: 30 } });

In this example, the $gte operator checks for values greater than or equal to 30.

Example of FindOne

If you want to find a single document, you can use findOne(). This method returns the first document that matches the query criteria:

db.users.findOne({ name: "Alice" });

This command fetches the document for Alice, if it exists, without returning all matching documents.

Update Operation

The Update operation allows you to modify existing documents in a collection. You can update a single document or multiple documents using the updateOne(), updateMany(), or the replaceOne() methods.

Example of UpdateOne

To update a single document, use updateOne():

db.users.updateOne(
  { name: "Alice" }, // Filter
  { $set: { age: 31 }} // Update
);

In this example, we are updating Alice's age to 31. The $set operator specifies which fields to update without altering other fields in the document.

Example of UpdateMany

If you want to update multiple documents that match certain criteria, you can use updateMany():

db.users.updateMany(
  { age: { $lt: 30 } }, // Filter for users under 30
  { $set: { status: "young" }} // Update to set status
);

Here, we’re setting the status to “young” for all users younger than 30.

Example of ReplaceOne

If you wish to replace an entire document instead of updating specific fields, use replaceOne():

db.users.replaceOne(
  { name: "Charlie" }, // Filter
  { name: "Charlie", age: 29, email: "charlie_new@example.com", status: "young" } // New document
);

In this case, we replace Charlie’s document fully with a new one.

Delete Operation

The Delete operation allows you to remove documents from a collection. You can delete one or multiple documents using the deleteOne() or deleteMany() methods.

Example of DeleteOne

To remove a single document, use deleteOne():

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

This command will delete Alice's document from the users collection.

Example of DeleteMany

To delete multiple documents that match certain criteria, use deleteMany():

db.users.deleteMany({ age: { $lt: 30 } });

This command will remove all users younger than 30.

Conclusion

Understanding CRUD operations is essential for anyone working with MongoDB. These operations form the backbone of how you manage data within your database.

  • Create: Use insertOne or insertMany to add documents.
  • Read: Retrieve documents with find() or findOne().
  • Update: Modify existing documents using updateOne(), updateMany() or replaceOne().
  • Delete: Remove unwanted documents with deleteOne() or deleteMany().

With these basics under your belt, you're well on your way to mastering data manipulation in MongoDB! Happy coding!