CRUD Operations

CRUD stands for Create, Read, Update, and Delete. These are the basic operations you can perform on a database. In MongoDB, a popular NoSQL database, CRUD operations are crucial for interacting with the data stored in the database. This chapter will provide a comprehensive overview of CRUD operations, from basic to advanced, with detailed explanations and code examples.

Create Operations

Create operations in MongoDB are used to insert documents into a collection.

Inserting a Single Document

To insert a single document into a MongoDB collection, use the insertOne method.

Example:

				
					db.collection.insertOne({
    name: "Alice",
    age: 30,
    city: "New York"
});

				
			

Explanation:

  • db.collection: Specifies the collection where the document will be inserted.
  • insertOne: Method used to insert a single document.
  • The document contains key-value pairs representing the data.
				
					{
    acknowledged: true,
    insertedId: ObjectId("5f8d0d55b54764421b7156d4")
}

				
			

Inserting Multiple Documents

To insert multiple documents at once, use the insertMany method.

Example:

				
					db.collection.insertMany([
    { name: "Bob", age: 25, city: "San Francisco" },
    { name: "Carol", age: 27, city: "Chicago" }
]);

				
			

Explanation:

  • insertMany: Method used to insert multiple documents.
  • The array contains documents to be inserted.
				
					{
    acknowledged: true,
    insertedIds: [
        ObjectId("5f8d0d55b54764421b7156d5"),
        ObjectId("5f8d0d55b54764421b7156d6")
    ]
}

				
			

Read Operations

Read operations in MongoDB allow you to retrieve documents from a collection.

Querying a Single Document

To query a single document, use the findOne method.

Example:

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

				
			

Explanation:

  • findOne: Method used to retrieve a single document matching the query.
  • The query { name: "Alice" } specifies the criteria for finding the document.
				
					{
    _id: ObjectId("5f8d0d55b54764421b7156d4"),
    name: "Alice",
    age: 30,
    city: "New York"
}

				
			

Querying Multiple Documents

To query multiple documents, use the find method.

Example:

				
					db.collection.find({ city: "Chicago" });

				
			

Explanation:

  • find: Method used to retrieve multiple documents matching the query.
  • The query { city: "Chicago" } specifies the criteria for finding the documents.
				
					[
    { _id: ObjectId("5f8d0d55b54764421b7156d6"), name: "Carol", age: 27, city: "Chicago" }
]

				
			

Query Operators

MongoDB provides various query operators to refine your search.

Example:

				
					db.collection.find({ age: { $gt: 25 } });

				
			

Explanation:

  • $gt: Operator for “greater than”.
  • The query { age: { $gt: 25 } } retrieves documents where the age is greater than 25.
				
					[
    { _id: ObjectId("5f8d0d55b54764421b7156d4"), name: "Alice", age: 30, city: "New York" },
    { _id: ObjectId("5f8d0d55b54764421b7156d6"), name: "Carol", age: 27, city: "Chicago" }
]

				
			

Projection

Projection allows you to specify which fields to include or exclude in the returned documents.

Example:

				
					db.collection.find({ city: "Chicago" }, { name: 1, _id: 0 });

				
			

Explanation:

  • The query { city: "Chicago" } specifies the criteria for finding the documents.
  • The projection { name: 1, _id: 0 } includes only the name field and excludes the _id field in the result.
				
					[
    { name: "Carol" }
]

				
			

Update Operations

Update operations in MongoDB are used to modify existing documents.

Updating a Single Document

To update a single document, use the updateOne method.

Example:

				
					db.collection.updateOne(
    { name: "Alice" },
    { $set: { age: 31 } }
);

				
			

Explanation:

  • updateOne: Method used to update a single document.
  • The query { name: "Alice" } specifies the document to update.
  • The update operation { $set: { age: 31 } } sets the age to 31.
				
					{
    acknowledged: true,
    matchedCount: 1,
    modifiedCount: 1
}

				
			

Updating Multiple Documents

To update multiple documents, use the updateMany method.

Example:

				
					db.collection.updateMany(
    { city: "Chicago" },
    { $set: { city: "Houston" } }
);

				
			

Explanation:

  • updateMany: Method used to update multiple documents.
  • The query { city: "Chicago" } specifies the documents to update.
  • The update operation { $set: { city: "Houston" } } sets the city to Houston.
				
					{
    acknowledged: true,
    matchedCount: 1,
    modifiedCount: 1
}

				
			

Update Operators

MongoDB provides various update operators to modify documents.

Example:

				
					db.collection.updateOne(
    { name: "Bob" },
    { $inc: { age: 1 } }
);

				
			

Explanation:

  • $inc: Operator to increment a field by a specified value.
  • The update operation { $inc: { age: 1 } } increments the age by 1.
				
					{
    acknowledged: true,
    matchedCount: 1,
    modifiedCount: 1
}

				
			

Delete Operations

Delete operations in MongoDB are used to remove documents from a collection.

Deleting a Single Document

To delete a single document, use the deleteOne method.

Example:

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

				
			

Explanation:

  • deleteOne: Method used to delete a single document.
  • The query { name: "Alice" } specifies the document to delete.
				
					{
    acknowledged: true,
    deletedCount: 1
}

				
			

Deleting Multiple Documents

To delete multiple documents, use the deleteMany method.

Example:

				
					db.collection.deleteMany({ city: "Houston" });

				
			

Explanation:

  • deleteMany: Method used to delete multiple documents.
  • The query { city: "Houston" } specifies the documents to delete.
				
					{
    acknowledged: true,
    deletedCount: 1
}

				
			

Advanced CRUD Operations

Bulk Write Operations

MongoDB allows you to perform multiple write operations in a single request using bulk writes.

Example:

				
					db.collection.bulkWrite([
    { insertOne: { document: { name: "Dave", age: 22, city: "Boston" } } },
    { updateOne: { filter: { name: "Bob" }, update: { $set: { age: 26 } } } },
    { deleteOne: { filter: { name: "Carol" } } }
]);

				
			

Explanation:

  • bulkWrite: Method used to perform multiple write operations.
  • The array contains various write operations (insert, update, delete).
				
					{
    acknowledged: true,
    insertedCount: 1,
    matchedCount: 1,
    modifiedCount: 1,
    deletedCount: 1
}

				
			

Using Aggregation Framework

The aggregation framework allows you to perform complex data processing and analysis.

Example:

				
					db.collection.aggregate([
    { $match: { city: "New York" } },
    { $group: { _id: "$city", averageAge: { $avg: "$age" } } }
]);

				
			

Explanation:

  • aggregate: Method used to perform aggregation operations.
  • The pipeline stages $match and $group filter and group the data, respectively.
  • The $avg operator calculates the average age.
				
					[
    { _id: "New York", averageAge: 30 }
]

				
			

In this chapter, we explored the fundamental CRUD operations in MongoDB, from basic to advanced. We learned how to create, read, update, and delete documents in a MongoDB collection, as well as perform bulk write operations and use the aggregation framework for complex queries. Mastering these operations is essential for effectively managing and interacting with your MongoDB database. Happy coding !❤️

Table of Contents