Aggregation in Golang mgo for Mongodb

前端 未结 2 1503
醉话见心
醉话见心 2021-02-14 04:45

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:Obje         


        
2条回答
  •  误落风尘
    2021-02-14 05:27

    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": "three@four.com",
                "count": 10
            },
            {
                "_id": "one@two.com",
                "count": 12
            }
        ]
    }
    

提交回复
热议问题