Golang mgo中的聚合操作用于Mongodb

13

有人知道在 golang mgo/bson 中,与我们在 mongodb shell 中使用的 aggregate 命令相当的命令吗?

类似于这样:

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
我现在无法写出完整的答案,但你可以使用mgo中的Pipe函数,参见http://godoc.org/labix.org/v2/mgo#Collection.Pipe。 - fmpwizard
2个回答

27

假设c是你的集合:

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参考文档:


如何从resp中获取嵌套值?我可以获取resp["someKey"],但无法获取resp["someKey"]["someKeyKey"]。 - Angger
有没有办法计算 pipe 的总值,而不是将它们全部放入一个切片中? - Lê Quang Bảo

2

样例代码:

最初的回答:
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)

注意:

请注意,如果您没有在逗号后断行,即使您的查询正确,它也会抛出错误消息。因此,请确保每行以逗号结尾。

输出结果:

{
    "transactions": [
        {
            "_id": "three@four.com",
            "count": 10
        },
        {
            "_id": "one@two.com",
            "count": 12
        }
    ]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接