group mongodb aggregation 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: group by mongo

db.sales.aggregate([
  // First Stage
  {
    $match : { "date": { $gte: new ISODate("2014-01-01"), $lt: new ISODate("2015-01-01") } }
  },
  // Second Stage
  {
    $group : {
       _id : { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
       totalSaleAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
       averageQuantity: { $avg: "$quantity" },
       count: { $sum: 1 }
    }
  },
  // Third Stage
  {
    $sort : { totalSaleAmount: -1 }
  }
 ])

Tags:

Misc Example