mongodb - 如何在带有库mgo的golang中使用$ facet?

标签 mongodb go mgo

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

{
    "product" : "car",
    "colour" : "red",
    "year" : "2019"
}
{
    "product" : "car",
    "colour" : "black",
    "year" : "2018"
}
{
    "product" : "bike",
    "colour" : "blue",
    "year" : "2014"
}
{
    "product" : "train",
    "colour" : "black",
    "year" : "2019"
}
{
    "product" : "ship",
    "colour" : "red",
    "year" : "2018"
}
{
    "product" : "car",
    "colour" : "red",
    "year" : "2016"
}
{
    "product" : "car",
    "colour" : "blue",
    "year" : "2015"
}
{
    "product" : "bike",
    "colour" : "white",
    "year" : "2014"
}
{
    "product" : "train",
    "colour" : "red",
    "year" : "2016"
}
{
    "product" : "ship",
    "colour" : "red",
    "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上实现相同的查询并将结果设置为struct?

最佳答案

使用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)

关于mongodb - 如何在带有库mgo的golang中使用$ facet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58802198/

相关文章:

javascript - 如何使属性动态化(在执行代码之前未知)?

go - 使用 Golang 的 SSH 指纹

mongodb - 使用 time.Time 字段插入文档时设置默认日期

java - 在 MongoDB 中存储多个 JSON 文档(具有嵌套 JSON 键值对象的行数组格式)

mongodb - Docker:更改存储 docker 卷的文件夹

戈朗 : Convert date with time to seconds

go - 在 go 中读取 windows 属性

使用 go 动态进行 mongodb 查询

go - Go的MongoDB独特查询和$ in

node.js - 如何在 sails 中使用 upsert、$inc、$set?