mongodb group by aggregate code example
Example 1: mongodb group by having
query = db.collection.aggregate([
{
"$group": { "_id": "$your_field",
"count": {"$sum":1} }
},
{ "$match": { "count": { "$gt": N } } }
])
Example 2: mongodb aggregate group
query = db.collection.aggregate([
{
"$group": {
"_id": "$your_field",
"total": {"$sum":1}
}
}
])
Example 3: group by mongo
db.books.aggregate([
// First Stage
{
$group : { _id : "$author", books: { $push: "$$ROOT" } }
},
// Second Stage
{
$addFields:
{
totalCopies : { $sum: "$books.copies" }
}
}
])