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


Assuming which 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 working

      



GoDoc links:

+22


source


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







All Articles