1

我想通过使用对字段求和

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

有什么解决办法吗?

4

1 回答 1

1

首先,Collection.Aggregate()返回 a mongo.Cursor,而不是“直接”结果。您必须遍历光标以获取结果文档(例如,使用Cursor.Next()and Cursor.Decode()),或用于Cursor.All()一步获取所有结果文档。

接下来,您没有指定要对哪个字段求和。您所拥有的是一个简单的“计数”,它将返回已处理的文档数量。要真正总结一个领域,你可以这样做

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

让我们看一个例子。假设我们在 Database 中有以下文档"example",在 collection 中"checks"

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

这就是我们如何计算支票并汇总付款(payment字段)的方式:

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

于 2019-11-21T20:35:09.167 回答