在Golang的mgo中进行Mongodb的聚合操作。

huangapple go评论73阅读模式
英文:

Aggregation in Golang mgo for Mongodb

问题

有人知道在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"}}}])
英文:

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

得分: 27

假设c是你的集合:

pipe := c.Pipe([]bson.M{{"$match": bson.M{"name":"John"}}})
resp := []bson.M{}
err := pipe.All(&resp)
if err != nil {
  //处理错误
}
fmt.Println(resp) //简单打印以证明它正常工作

GoDoc 参考文档:

英文:

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:

答案2

得分: 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
        }
    ]
}
英文:

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
        }
    ]
}

huangapple
  • 本文由 发表于 2014年10月20日 07:04:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/26456375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定