MONGODB2
MONGODB2
// $match Stage---------------------------
db.sales.aggregate([
{
$match: { status: "A" }
}
])
db.sales.aggregate([
{
$match: {
date: {
$gte: ISODate("2024-01-01"),
$lt: ISODate("2024-02-01")
}
}
}
])
db.sales.aggregate([
{
$match: { quantity: { $gt: 2 } }
}
])
db.sales.aggregate([
{
$match: { category: "Electronics" }
}
])
// -----------------------------------------------------
//group
db.sales.aggregate([
{
$group: {
_id: "$product",
totalQuantitySold: { $sum: "$quantity" }
}
}
])
db.sales.aggregate([
{
$group: {
_id: null,
totalAmountSpent: { $sum: "$amount" }
}
}
])
db.sales.aggregate([
{
$match: { status: "B" },
$count: {"total statusof B:"}
}
])
db.sales.aggregate([{
$group: {_id:null,
amount:{$avg:"$amount"}
}}]);
// ---------------------------------------------------sort
db.sales.aggregate([
{
$sort: {amount:-1}
}
])
db.sales.aggregate([
{
$group: {
_id: "$customerId",
totalSpending: { $sum: "$amount" }
}
},
{
$sort: { totalSpending: -1 }
}
]);
db.sales.aggregate([
{
$sort:{"date": 1}
}])
db.sales.aggregate([{
$sort:{amount:-1}
}])
// project ----------------
db.sales.aggregate([
{
$project: {
product: 1,
amount: 1,
_id: 0
}
}
]);
db.sales.aggregate([
{
$project: {
totalSpent: "$amount",
}
}
]);
db.sales.aggregate([
{
$project:{
customerId:1,
customer:1
}
}])
// limit---------------------
db.sales.aggregate([
{
$project: {
customerId:1,
_id: 0
}
},
{
$limit: 3
}
]);
// SKIP---------------------------
db.sales.aggregate([
{
$project: {
product: 1,
amount: 1,
_id: 0
}
},
{
$skip: 1
}
]);
db.customers.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerDetails"
}
},
{
$unwind: "$customerDetails"
},
{
$match: {
"customerDetails.name": { $regex: /^A/ }
}
}
])
// add fields
db.sales.aggregate([
{
$addFields: {
totalPrice: { $multiply: ["$amount", "$quantity"] }
}
}
])