登录
首页 >  Golang >  Go问答

Golang 使用 MongoDB 进行多值聚合组

来源:stackoverflow

时间:2024-02-14 20:36:25 448浏览 收藏

你在学习Golang相关的知识吗?本文《Golang 使用 MongoDB 进行多值聚合组》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我正在尝试使用组运算符和多个值进行聚合

我在 mongodb 中做了这个查询:

db.modules.aggregate([{$group: {_id: {"module":"$module","host":"$host"},"status":{$last:"$status"}}}])

我使用包:go.mongodb.org

我想在 golang 代码中实现它:

group := bson.d{{"$group", bson.d{{"_id", bson.d{{"module", "$module", "host", "$host"}}}, {"time", bson.d{{"$last","$time"}}}, {"level", bson.d{{"$last","$level"}}}}}}

cursor, err := collection.aggregate(ctx, mongo.pipeline{group})
if err != nil {
    fmt.println("failed to aggregate: ", err)
}
defer cursor.close(ctx)
if err = cursor.all(ctx, &results); err != nil {
    fmt.printf("cursor.all() error:", err)
}

当我想编译代码时,它返回以下错误:

too many values in primitive.E{...}

谁能告诉我我的组中的错误在哪里。感谢您的帮助!


正确答案


问题出在这个带有复合文字的片段上:

bson.d{{"module", "$module", "host", "$host"}}

bson.D是一个字段切片,其中字段是键值对(即:2个元素),并且您尝试定义一个具有4个值的元素(一个字段)。

应该是:

bson.d{{"module", "$module"}, {"host", "$host"}}

一般来说,您应该将这些表达式格式化为多行。更容易阅读、更容易理解、更容易修改。

例如:

group := bson.D{
    {
        "$group", bson.D{
            {
                "_id", bson.D{
                    {"module", "$module"},
                    {"host", "$host"},
                },
            },
            {"time", bson.D{{"$last", "$time"}}},
            {"level", bson.D{{"$last", "$level"}}},
        },
    },
}

今天关于《Golang 使用 MongoDB 进行多值聚合组》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>