group by mongo code example
Example 1: group by mongo
db.sales.aggregate([
{
$match : { "date": { $gte: new ISODate("2014-01-01"), $lt: new ISODate("2015-01-01") } }
},
{
$group : {
_id : { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
totalSaleAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
averageQuantity: { $avg: "$quantity" },
count: { $sum: 1 }
}
},
{
$sort : { totalSaleAmount: -1 }
}
])
Example 2: group by mongo
db.books.aggregate([
{
$group : { _id : "$author", books: { $push: "$$ROOT" } }
},
{
$addFields:
{
totalCopies : { $sum: "$books.copies" }
}
}
])