mongodb - mongo-go-driver聚合查询总是返回 "Current": null

标签 mongodb go mongodb-query aggregation-framework mongo-go

我想使用

对字段求和
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()返回 mongo.Cursor ,而不是“直接”结果。您必须迭代光标才能获取结果文档(例如使用 Cursor.Next()Cursor.Decode() ),或使用 Cursor.All()一步获取所有结果文档。

接下来,您没有指定要求和的字段。您所拥有的是一个简单的“计数”,它将返回已处理的文档数量。要真正对字段求和,您可以使用

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

让我们看一个例子。假设数据库 "example" 集合 "checks" 中有以下文档:

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

这就是我们计算支票并对付款求和的方式(付款字段):

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]]

结果是一个只有一个元素的 slice ,显示已处理 3 个文档,并且(付款)总和为 34

关于mongodb - mongo-go-driver聚合查询总是返回 "Current": null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58981825/

相关文章:

javascript - 如何从 Mongoose 中的多个数组更新数组内的值?

arrays - 在 Go 中解码顶级 JSON 数组

go time.Parser 错误,日期为 DMYYYY

Mongodb聚合-排序使得查询非常慢

mongodb - 在 mongodb 中对组查询的结果进行分组

python - 使用 $set 和位置 $ 运算符更新集合中数组中的文档

mongodb - 在mongodb中获取具有相同属性的文档

mongodb - 使用 MongoDB 投影数组

mongodb - 如何连接 MongoDB 中多个文档的数组?

go - 实现梯度下降