本文介绍了如何使用mongo-driver在Go中执行聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含3个字段的MongoDB集合:

I have a MongoDB collection with 3 fields:

_id: ObjectId
field1: Number
field2: Number

我正在执行此聚合以获取不同的" field1/field2行,并对结果进行总计.可以在客户端(Robo3t)中正常运行:

I am doing this aggregation to get "distinct" field1/field2 rows and doing a total count of the results. This works OK in the client (Robo3t):

db.mycollection.aggregate([
    {
        $group: { 
            _id: { field1: "$field1", field2: "$field2" },
        }
    },
    { 
        $group: { 
            _id: null, count: { $sum: 1 } 
        } 
    }
])

结果:

{
    "_id" : null,
    "count" : 57.0
}

如何使用 mongo-driver在Go中进行聚合?

How could I do this aggregation in Go using mongo-driver?

方法来执行聚合但是文档对我来说还不清楚.我知道我应该进行某种bson查询,但是我不知道从哪里开始.

There is this method to perform aggregations but the documentation is not clear to me. I understand that I should do some kind of bson query but I don't know where to start.

推荐答案

group :=[]bson.M{bson.M{
    "$group": bson.M{
        "_id":bson.M{
            "field1": "$field1",
            "field2": "$field2"
        }
    }
},
bson.M {
    "$group": bson.M{
        "_id":nil,
        "count": bson.M{
            "$sum":1
        }
    }
}
} 

cursor, err := coll.Aggregate(context.Background(), mongo.Pipeline{group})
if err != nil {
    log.Fatal(err)
}

尝试上述解决方案,它将起作用.

Try the above solution, It will works.

这篇关于如何使用mongo-driver在Go中执行聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 16:00