Lab-MongoDB Aggregation and MapReduce
Lab-MongoDB Aggregation and MapReduce
3. $match stage
db.orders.aggregate( [
{ $match : { status : "A" } }
])
db.orders.aggregate( [
{ $match : { cust_id: "A123" , status : "A" } }
])
db.orders.aggregate ( [
{ $match : { $or: [ {amount: {$gte: 300}} , {status : "D"} ] } }
])
4. $group stage
db.orders.aggregate ( [
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } }
])
From MongoDB 5.0, we can use $count in $group stage to get the number of documents in
a group directly. We can rewrite the above command as follows
db.orders.aggregate ( [
{ $match : { status : "A" } },
{ $group: { _id: null, order_count: { $count: { } } } }
])
8. $sort
db.orders.aggregate ( [
{ $match : { status : "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort : { _id : 1 } }
] );
db.orders.aggregate ( [
{ $match : { status : "A" } },
{ $group: {_id: "$cust_id", avg_amount: { $avg: "$amount" } } }
])
What is the difference between the above two commands?
The following aggregation uses the $unwind stage to output a document for each element
in the sizes array:
db.inventory.aggregate( [
{ $unwind: "$sizes" }
])
db.inventory2.insertMany( [
{ "_id" : 1, "item" : "ABC", price: NumberDecimal("80"), "sizes" : [ "S", "M", "L" ] },
{ "_id" : 2, "item" : "EFG", price: NumberDecimal("120"), "sizes" : [ ] },
{ "_id" : 3, "item" : "IJK", price: NumberDecimal("160"), "sizes" : "M" },
{ "_id" : 4, "item" : "LMN" , price: NumberDecimal("10") },
{ "_id" : 5, "item" : "XYZ", price: NumberDecimal("5.75"), "sizes" : null }
])
db.inventory2.aggregate( [
{
$unwind:
{
path: "$sizes",
includeArrayIndex: "arrayIndex"
}
}
])
You may also try to add preserveNullAndEmptyArrays: true to see what will happen.
db.inventory2.aggregate( [
{
$unwind:
{
path: "$sizes",
preserveNullAndEmptyArrays: true,
includeArrayIndex: "arrayIndex"
}
}
])
db.inventory2.aggregate( [
// First Stage
{
$unwind: { path: "$sizes", preserveNullAndEmptyArrays: true }
},
// Second Stage
{
$group:
{
_id: "$sizes",
averagePrice: { $avg: "$price" }
}
},
// Third Stage
{
$sort: { "averagePrice": -1 }
}
])
db.sales.insertMany([
{
_id: "1",
"items" : [
{
"name" : "pens",
"tags" : [ "writing", "office", "school", "stationary" ],
"price" : NumberDecimal("12.00"),
"quantity" : NumberInt("5")
},
{
"name" : "envelopes",
"tags" : [ "stationary", "office" ],
"price" : NumberDecimal("1.95"),
"quantity" : NumberInt("8")
}
]
},
{
_id: "2",
"items" : [
{
"name" : "laptop",
"tags" : [ "office", "electronics" ],
"price" : NumberDecimal("800.00"),
"quantity" : NumberInt("1")
},
{
"name" : "notepad",
"tags" : [ "stationary", "school" ],
"price" : NumberDecimal("14.95"),
"quantity" : NumberInt("3")
}
]
}
])
db.sales.aggregate( [
// First Stage
{ $unwind: "$items" },
// Second Stage
{ $unwind: "$items.tags" },
// Third Stage
{
$group:
{
_id: "$items.tags",
totalSalesAmount:
{
$sum: { $multiply: [ "$items.price", "$items.quantity" ] }
}
}
}
])
db.orders.mapReduce(
function() { emit(this.cust_id , this.amount); },
function(key, values) { return Array.sum(values) },
{
query: { status: "A" },
out: "order_totals"
}
)
Create another collection inventory with the following documents (delete the documents in
inventory first if there are any):
db.inventory.insertMany( [
{ _id : 1, sku : "almonds", description: "product 1", instock : 120 },
{ _id : 2, sku : "bread", description: "product 2", instock : 80 },
{ _id : 3, sku : "cashews", description: "product 3", instock : 60 },
{ _id : 4, sku : "pecans", description: "product 4", instock : 70 },
{ _id : 5, sku : null, description: "Incomplete" },
{ _id : 6 }
])
db.orders.aggregate( [
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
}
])
The operation would correspond to the following pseudo-SQL statement:
SELECT *, inventory_docs
FROM orders
WHERE inventory_docs IN (SELECT *
FROM inventory
WHERE sku = orders.item);
References
https://www.tutorialspoint.com/mongodb/mongodb_aggregation.htm
https://docs.mongodb.com/manual/
https://appdividend.com/2018/10/25/mongodb-aggregate-example-tutorial/
https://appdividend.com/2018/10/26/mongodb-mapreduce-example-tutorial/
https://docs.mongodb.com/manual/reference/method/db.collection.distinct/
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
The course materials are only for the use of students enrolled in the course CSIS 3300 at Douglas
College. Sharing this material to a third-party website can lead to a violation of Copyright law.