Today’s new knowledge #2
kishor sutradhar
Posted on November 11, 2024
Today's Overview:
Hello again, everyone! Yesterday, I learned the basics of MongoDB CRUD operations and some field filtering operators. Today, I didn’t do as much since I watched a few episodes of Blue Lock season 2. After that, I decided to update my resume, so I started working on it in Figma. If anyone has suggestions or tips for improving my resume, I’d love to hear them!
I still wanted to learn something new today. here’s what I covered. the first thing i learned is mongodb aggregation framework.
Mongodb Aggregation Framework
The aggregation framework operates on collections of documents and processes them through stages in a pipeline, with each stage applying a specific transformation. you have to use *db.collection.aggregate() *
You can use db.collection.find()
for simple queries and filtering, and db.collection.aggregate()
for complex queries and filtering. Here are some of the most used aggregate operators.
Mongodb Aggregation operators
$match
, $project
, $addFields
, $out
, $merge
Example:
Imagine we have a sales
collection with the following documents:
[
{ "_id": 1, "product": "laptop", "category": "electronics", "quantity": 2, "price": 800, "storeLocation": "New York", "date": "2024-11-01" },
{ "_id": 2, "product": "smartphone", "category": "electronics", "quantity": 5, "price": 500, "storeLocation": "Los Angeles", "date": "2024-11-02" },
{ "_id": 3, "product": "laptop", "category": "electronics", "quantity": 1, "price": 800, "storeLocation": "Chicago", "date": "2024-11-03" },
{ "_id": 4, "product": "desk", "category": "furniture", "quantity": 3, "price": 150, "storeLocation": "New York", "date": "2024-11-04" },
{ "_id": 5, "product": "chair", "category": "furniture", "quantity": 10, "price": 75, "storeLocation": "Los Angeles", "date": "2024-11-05" }
]
$match
: Filters documents based on specified criteria (similar to the find operation)
db.sales.aggregate([
{ $match: { category: "electronics" } }
])
//output
[
{ "_id": 1, "product": "laptop", "category": "electronics", "quantity": 2, "price": 800, "storeLocation": "New York", "date": "2024-11-01" },
{ "_id": 2, "product": "smartphone", "category": "electronics", "quantity": 5, "price": 500, "storeLocation": "Los Angeles", "date": "2024-11-02" },
{ "_id": 3, "product": "laptop", "category": "electronics", "quantity": 1, "price": 800, "storeLocation": "Chicago", "date": "2024-11-03" }
]
The $project
stage allows you to control which fields to include or exclude.
db.sales.aggregate([
{
$project: { product: 1, quantity: 1, price: 1,}}
}
])
/// output
[
{ "_id": 1, "product": "laptop", "quantity": 2, "price": 800, },
{ "_id": 2, "product": "smartphone", "quantity": 5, "price": 500, },
{ "_id": 3, "product": "laptop", "quantity": 1, "price": 800, },
{ "_id": 4, "product": "desk", "quantity": 3, "price": 150, },
{ "_id": 5, "product": "chair", "quantity": 10, "price": 75, }
]
We can use $addFields
to add a new field to the document. The special thing is that $addFields does not modify the original document.
db.sales.aggregate([
{
$addFields: {
totalPrice: { $multiply: ["$price", "$quantity"] }
}
}
])
//output
[
{ "_id": 1, "product": "laptop", "category": "electronics", "quantity": 2, "price": 800, "storeLocation": "New York", "date": "2024-11-01", "totalPrice": 1600 },
{ "_id": 2, "product": "smartphone", "category": "electronics", "quantity": 5, "price": 500, "storeLocation": "Los Angeles", "date": "2024-11-02", "totalPrice": 2500 },
{ "_id": 3, "product": "laptop", "category": "electronics", "quantity": 1, "price": 800, "storeLocation": "Chicago", "date": "2024-11-03", "totalPrice": 800 },
{ "_id": 4, "product": "desk", "category": "furniture", "quantity": 3, "price": 150, "storeLocation": "New York", "date": "2024-11-04", "totalPrice": 450 },
{ "_id": 5, "product": "chair", "category": "furniture", "quantity": 10, "price": 75, "storeLocation": "Los Angeles", "date": "2024-11-05", "totalPrice": 750 }
]
New field totalPrice
is added to each document in the pipeline
$multiply
is an aggregation operator used in MongoDB's aggregation pipeline to multiply numeric values.
The $out
stage in MongoDB aggregation pipelines writes the results of a pipeline to a specified collection. The $out
stage replaces the target collection if it exists, so use it carefully.
db.sales.aggregate([
{
$addFields: {
totalPrice: { $multiply: ["$price", "$quantity"] }
}
},
{
$out: "salesWithTotalPrice"
}
])
$addFields
: Adds the totalPrice field to each document by multiplying price and quantity.
$out
: Writes the transformed documents to the salesWithTotalPrice collection.
The $merge stage in MongoDB is similar to $out but more flexible. While $out replaces the entire target collection, $merge allows you to merge the results of an aggregation pipeline into an existing collection, with options to update, insert, or keep the existing documents.
db.sales.aggregate([
{
$addFields: {
totalPrice: { $multiply: ["$price", "$quantity"]}
}
},
{
$merge: {
into: "salesWithTotalPrice",
whenMatched: "merge", // Update existing documents by merging fields
whenNotMatched: "insert" // Insert new documents if no match is found
}
}
])
If using all default options for $merge
, including writing to a collection in the same database, you can use the simplified form
db.sales.aggregate([
{
$addFields: {
totalPrice: { $multiply: ["$price", "$quantity"]}
}
},
{ $merge: "salesWithTotalPrice" }
}
])
That's all I learnd today. talk to you next time.
Posted on November 11, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.