如何在Golang中使用$ facet和库mgo?

我开始学习mongoDb的性能改进。而且我有一个基于问题的聚合函数。 我创建了一个包含3个字段产品,颜色和年份的基本测试集合:

{
    "product" : "car","colour" : "red","year" : "2019"
}
{
    "product" : "car","colour" : "black","year" : "2018"
}
{
    "product" : "bike","colour" : "blue","year" : "2014"
}
{
    "product" : "train","year" : "2019"
}
{
    "product" : "ship","year" : "2018"
}
{
    "product" : "car","year" : "2016"
}
{
    "product" : "car","year" : "2015"
}
{
    "product" : "bike","colour" : "white","year" : "2016"
}
{
    "product" : "ship","year" : "2015"
}

由于性能问题,我希望将facet用于单个聚合阶段:

 db.getcollection('test').aggregate([
    {
        "$match":{
            "colour":"red"
        }
    },{
        "$facet": {
            "cntOfReds":[
                {"$group":{"_id": "$product","count": {"$sum": 1}}}
            ],"cntOfRedsIn2015":[
                {"$match" :{"year": "2015"}},{"$group": {"_id": "$year","count": {"$sum": 1}}}
            ]
    }   }

    ])

我们如何使用mgo.v2在golang上实现相同的查询,并将结果设置为结构?

di880518 回答:如何在Golang中使用$ facet和库mgo?

使用mgo,您必须将一系列文档传递给Pipe

p:=collection.Pipe([]bson.M{
  {"$match": bson.M{"colour":"red"}},{"$facet": bson.M{ "cntOfReds":[]bson.M{{"$group":{"_id": "$product","count": bson.M{"$sum":1}}}}},"cntOfRedsIn2015": ...

然后,运行管道并获得结果:

p.All(&results)
,
res := Result{
        Cr: make([]CntOfReds,0),CrByYear: make([]CntOfReds,}


err = collection.Pipe([]bson.M{
        {"$match": bson.M{"colour": "red"}},{
            "$facet":
            bson.M{
                "cntOfReds": []bson.M{
                    {"$group": bson.M{"_id": "$product","count": bson.M{"$sum": 1}}},},"cntOfReds2": []bson.M{
                    {"$match": bson.M{"year": "2015"}},{"$group": bson.M{"_id": "$product",}).All(&res)

我认为这应该给我正确的答案。但现在由于结构而面临错误。您能帮我纠正一下结构吗?

panic:结果参数必须是一个分片地址

type Facet struct {
    Cr []CntOfReds `bson:"cntOfReds"`
    CrByYear []CntOfReds `bson:"cntOfRedsIn2015"`
}
type CntOfReds struct {
    Product string `bson:"_id"`
    Count int `bson:"count"`
}
本文链接:https://www.f2er.com/3123957.html

大家都在问