mongodb group by query example

Example 1: mongodb group by having

#It's the equivalent of the following SQL instruction:
# SELECT COUNT(*) FROM Table
# GROUP BY your_field
# HAVING COUNT(*) > N
query = db.collection.aggregate([

    { 
      "$group": { "_id": "$your_field", #GROUP BY your_field
    			"count": {"$sum":1} }   #COUNT(*)
    },
    
    { "$match": { "count": { "$gt": N } } } #HAVING COUNT(*) > N
])

Example 2: 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 3: group by mongo

db.books.aggregate([
   // First Stage
   {
     $group : { _id : "$author", books: { $push: "$$ROOT" } }
   },
   // Second Stage
   {
     $addFields:
       {
         totalCopies : { $sum: "$books.copies" }
       }
   }
 ])

Tags:

Misc Example