问题
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