mongodb aggregate group by multi element code example
Example 1: mongodb aggregate group
#equivalent of the following SQL instruction:
# SELECT COUNT(*) FROM Table
# GROUP BY your_field
query = db.collection.aggregate([
{
"$group": {
"_id": "$your_field", #GROUP BY your_field
"total": {"$sum":1} #COUNT(*)
}
}
])
Example 2: mongodb group by several fields
db.books.aggregate([
{ "$group": {
"_id": {
"addr": "$addr",
"book": "$book"
},
"bookCount": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.addr",
"books": {
"$push": {
"book": "$_id.book",
"count": "$bookCount"
},
},
"count": { "$sum": "$bookCount" }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$project": {
"books": { "$slice": [ "$books", 2 ] },
"count": 1
}}
])