英文:
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
}
]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论