1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

can i get the results in struct form instead of []bson.M from cursor.All ?
@nanakondor Have you tried it? Yes, you can. But it must be a slice of struct or slice of pointers to struct because in general the result of an aggregation is a list of documents.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.