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 in MongoDB are used to insert documents into a collection.
To insert a single document into a MongoDB collection, use the insertOne
method.
db.collection.insertOne({
name: "Alice",
age: 30,
city: "New York"
});
db.collection
: Specifies the collection where the document will be inserted.insertOne
: Method used to insert a single document.
{
acknowledged: true,
insertedId: ObjectId("5f8d0d55b54764421b7156d4")
}
To insert multiple documents at once, use the insertMany
method.
db.collection.insertMany([
{ name: "Bob", age: 25, city: "San Francisco" },
{ name: "Carol", age: 27, city: "Chicago" }
]);
insertMany
: Method used to insert multiple documents.
{
acknowledged: true,
insertedIds: [
ObjectId("5f8d0d55b54764421b7156d5"),
ObjectId("5f8d0d55b54764421b7156d6")
]
}
Read operations in MongoDB allow you to retrieve documents from a collection.
To query a single document, use the findOne
method.
db.collection.findOne({ name: "Alice" });
findOne
: Method used to retrieve a single document matching the query.{ name: "Alice" }
specifies the criteria for finding the document.
{
_id: ObjectId("5f8d0d55b54764421b7156d4"),
name: "Alice",
age: 30,
city: "New York"
}
To query multiple documents, use the find
method.
db.collection.find({ city: "Chicago" });
find
: Method used to retrieve multiple documents matching the query.{ city: "Chicago" }
specifies the criteria for finding the documents.
[
{ _id: ObjectId("5f8d0d55b54764421b7156d6"), name: "Carol", age: 27, city: "Chicago" }
]
MongoDB provides various query operators to refine your search.
db.collection.find({ age: { $gt: 25 } });
$gt
: Operator for “greater than”.{ 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 allows you to specify which fields to include or exclude in the returned documents.
db.collection.find({ city: "Chicago" }, { name: 1, _id: 0 });
{ city: "Chicago" }
specifies the criteria for finding the documents.{ name: 1, _id: 0 }
includes only the name
field and excludes the _id
field in the result.
[
{ name: "Carol" }
]
Update operations in MongoDB are used to modify existing documents.
To update a single document, use the updateOne
method.
db.collection.updateOne(
{ name: "Alice" },
{ $set: { age: 31 } }
);
updateOne
: Method used to update a single document.{ name: "Alice" }
specifies the document to update.{ $set: { age: 31 } }
sets the age to 31.
{
acknowledged: true,
matchedCount: 1,
modifiedCount: 1
}
To update multiple documents, use the updateMany
method.
db.collection.updateMany(
{ city: "Chicago" },
{ $set: { city: "Houston" } }
);
updateMany
: Method used to update multiple documents.{ city: "Chicago" }
specifies the documents to update.{ $set: { city: "Houston" } }
sets the city to Houston.
{
acknowledged: true,
matchedCount: 1,
modifiedCount: 1
}
MongoDB provides various update operators to modify documents.
db.collection.updateOne(
{ name: "Bob" },
{ $inc: { age: 1 } }
);
$inc
: Operator to increment a field by a specified value.{ $inc: { age: 1 } }
increments the age by 1.
{
acknowledged: true,
matchedCount: 1,
modifiedCount: 1
}
Delete operations in MongoDB are used to remove documents from a collection.
To delete a single document, use the deleteOne
method.
db.collection.deleteOne({ name: "Alice" });
deleteOne
: Method used to delete a single document.{ name: "Alice" }
specifies the document to delete.
{
acknowledged: true,
deletedCount: 1
}
To delete multiple documents, use the deleteMany
method.
db.collection.deleteMany({ city: "Houston" });
deleteMany
: Method used to delete multiple documents.{ city: "Houston" }
specifies the documents to delete.
{
acknowledged: true,
deletedCount: 1
}
MongoDB allows you to perform multiple write operations in a single request using bulk writes.
db.collection.bulkWrite([
{ insertOne: { document: { name: "Dave", age: 22, city: "Boston" } } },
{ updateOne: { filter: { name: "Bob" }, update: { $set: { age: 26 } } } },
{ deleteOne: { filter: { name: "Carol" } } }
]);
bulkWrite
: Method used to perform multiple write operations.
{
acknowledged: true,
insertedCount: 1,
matchedCount: 1,
modifiedCount: 1,
deletedCount: 1
}
The aggregation framework allows you to perform complex data processing and analysis.
db.collection.aggregate([
{ $match: { city: "New York" } },
{ $group: { _id: "$city", averageAge: { $avg: "$age" } } }
]);
aggregate
: Method used to perform aggregation operations.$match
and $group
filter and group the data, respectively.$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 !❤️