mongo-go-driver聚合查询始终返回“当前":null [英] mongo-go-driver aggregate query always return "Current": null
问题描述
我想使用
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)
但它总是返回
"Current": null
有解决方案吗?
推荐答案
首先, Collection.Aggregate()
返回 Cursor.Next()
和 Cursor.Decode()
),或使用 Cursor.All()
来一步即可获取所有结果文档.
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"}
让我们看一个例子.假设我们在数据库"example"
中的集合"checks"
中具有以下文档:
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 }
这是我们计算支票和付款总和的方式(payment
字段):
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)
这将输出:
[map[_id: count:3 sum:34]]
结果是一个包含一个元素的切片,显示处理了3
个文档,(付款的)总和是34
.
The result is a slice with one element, showing 3
documents were processed, and the sum (of payments) is 34
.
这篇关于mongo-go-driver聚合查询始终返回“当前":null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!