Aggregation in Golang mgo for Mongodb

Sample Code:

pipe := c.Pipe([]bson.M{bson.M{"$match": bson.M{"type": "stamp"}},
        bson.M{"$group": bson.M{"_id": "$userid",
            "count": bson.M{"$sum": "$noofsr"}}}})

resp := []bson.M{}
iter := pipe.Iter()
err = iter.All(&resp)

Note:

Please note that the line should end with (,) if you are not breaking in (,) it will throw error message even if your query is correct.

Output:

{
    "transactions": [
        {
            "_id": "[email protected]",
            "count": 10
        },
        {
            "_id": "[email protected]",
            "count": 12
        }
    ]
}

Assuming that c is your Collection:

pipe := c.Pipe([]bson.M{{"$match": bson.M{"name":"John"}}})
resp := []bson.M{}
err := pipe.All(&resp)
if err != nil {
  //handle error
}
fmt.Println(resp) // simple print proving it's working

GoDoc references:

  • Collection.Pipe documentation
  • Pipe and its methods