Aggregation in Golang mgo for Mongodb
Does anyone know what is the equivalent of the aggregate command we use in the mongodb shell for golang mgo / bson?
Something like that:
aggregate([{$match:{my_id:ObjectId("543d171c5b2c1242fe0019")}},{$sort:{my_id:1, dateInfo:1, name:1}},{$group:{_id:"$my_id", lastEntry:{$max: "$dateInfo"},nm:{$last:"$name"}}}])
+5
source to share
2 answers
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)
Notes:
Note that the line must end with (,), if you don't hack with (,), it will throw an error message even if your query is correct.
Output:
{
"transactions": [
{
"_id": "three@four.com",
"count": 10
},
{
"_id": "one@two.com",
"count": 12
}
]
}
0
source to share