mongo-go-driver aggregate query always return “Current”: null

[亡魂溺海] 提交于 2020-01-03 04:01:13

问题


I want to sum a field by using

pipeline := []bson.M{
    bson.M{"$group": bson.M{
        "_id": "", 
        "count": bson.M{ "$sum": 1}}}
}
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
result, err := collection.Aggregate(ctx, pipeline)

but it always return

"Current": null

Any solution?


回答1:


First, Collection.Aggregate() returns a mongo.Cursor, not the "direct" result. You have to iterate over the cursor to get the result documents (e.g. with Cursor.Next() and Cursor.Decode()), or use Cursor.All() to fetch all result documents in one step.

Next, you didn't specify which field you want to sum. What you have is a simple "counting", it will return the number of documents processed. To really sum a field, you may do it with

"sum": bson.M{"$sum": "$fieldName"}

Let's see an example. Let's assume we have the following documents in Database "example", in collection "checks":

{ "_id" : ObjectId("5dd6f24742be9bfe54b298cb"), "payment" : 10 }
{ "_id" : ObjectId("5dd6f24942be9bfe54b298cc"), "payment" : 20 }
{ "_id" : ObjectId("5dd6f48842be9bfe54b298cd"), "payment" : 4 }

This is how we could count the checks and sum the payments (payment field):

c := client.Database("example").Collection("checks")

pipe := []bson.M{
    {"$group": bson.M{
        "_id":   "",
        "sum":   bson.M{"$sum": "$payment"},
        "count": bson.M{"$sum": 1},
    }},
}
cursor, err := c.Aggregate(ctx, pipe)
if err != nil {
    panic(err)
}

var results []bson.M
if err = cursor.All(ctx, &results); err != nil {
    panic(err)
}
if err := cursor.Close(ctx); err != nil {
    panic(err)
}

fmt.Println(results)

This will output:

[map[_id: count:3 sum:34]]

The result is a slice with one element, showing 3 documents were processed, and the sum (of payments) is 34.



来源:https://stackoverflow.com/questions/58981825/mongo-go-driver-aggregate-query-always-return-current-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!