简体   繁体   中英

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

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?

First, Collection.Aggregate() returns a mongo.Cursor , not the "direct" result. You have to iterate over the cursor to get the result documents (eg withCursor.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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM