Aggregation in Golang mgo for Mongodb

2019-01-26 18:54发布

问题:

Anybody knows what’s the equivalent of aggregate command we use in 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"}}}])

回答1:

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