Skip to content

Aggregation Helper Examples

TylerBrock edited this page Nov 13, 2012 · 1 revision

Examples

Insert some data

db.users.insert([
  {
    "age": 27,
    "first_name": "Tyler",
    "last_name": "Brock",
    "updated": new Date()
  },
  { 
    "age": 30,
    "first_name": "Jessica",
    "last_name": "Fake",
    "updated": new Date()
  },
  {
    "age": 35,
    "first_name": "Tyler",
    "last_name": "Durden",
    "updated": new Date()
  }
])

Group and count users by the first_name field

db.users.gcount("first_name")
{
  "result": [
    {
      "_id": "Jessica",
      "count": 1
    },
    {
      "_id": "Tyler",
      "count": 2
    }
  ],
  "ok": 1
}

Group and count users having first_name of Tyler

db.users.gcount("first_name", {first_name: "Tyler"})
{
  "result": [
    {
      "_id": "Tyler",
      "count": 2
    }
  ],
  "ok": 1
}

Group users by first name and sum the age field

db.users.gsum("first_name", "age")
{
  "result": [
    {
      "_id": "Jessica",
      "sum": 30
    },
    {
      "_id": "Tyler",
      "sum": 62
    }
  ],
  "ok": 1
}

Group users by first name and average the age field

db.users.gavg("first_name", "age")
{
  "result": [
    {
      "_id": "Jessica",
      "avg": 30
    },
    {
      "_id": "Tyler",
      "avg": 31
    }
  ],
  "ok": 1
}