登录
首页 >  Golang >  Go问答

在 MongoDB 使用 Golang 实现条件附加

来源:stackoverflow

时间:2024-03-01 19:15:24 167浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《在 MongoDB 使用 Golang 实现条件附加》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我是使用 mongo db 的新手,并尝试在 golang 中编写此 mongo 查询。 基本上,我尝试根据下面给出的某些情况将字段 ready 设置为 truefalse

db.getcollection('product_repo').update({catalog_global_id: "123-def-xyz"}, [{
    $set: {
        "ready": {
            $cond: [
              {$and: [
                  {$ne: ["enable_catalog", null]}, 
                  {$ne: ["enable_pricing", null]}
              ]}, true, false
            ]
        }
    }
}])

现在,我在 golang 中的 go 查询如下所示。

query := []bson.m{
        {
            "$cond": bson.m{
                "$if": bson.m{
                    "$ne": bson.m{
                        "enable_catalog": nil,
                    },
                },
                "then": true,
                "else": false,
            },
        },
    }

问题是,只有启用该标志后才会添加我的字段 "$enable_pricing" ,所以这就是我陷入困境的地方。我尝试这样做。

if isPricingEnabled() {
        query = append(clauses, bson.M{
            "$ne": bson.M{
                "pricing_attributes": nil,
            },
        })
    }

现在,我知道我在这里做错了什么,因为我的 golang 查询失败了,但不确定我错过了什么以及我能做些什么来修复它。我在这里可能会错过什么?


正确答案


在形成查询之前,您可以像这样创建 and 块。 然后在最终查询中使用它

andQuery := []bson.M{{
        "$ne": bson.A{"anable_catalog", nil},
    }}

if isPricingEnabled(){
        andQuery = append(andQuery, bson.M{"$ne": bson.A{ "enable_pricing", nil}})
}
query := bson.M{
    "$cond": bson.M{
        "if": bson.M{
            "$and": andQuery,
        },
        "then": true,
        "else": false,
    },
}
var updateData  = bson.M{
    "$set": bson.M{
        "ready" : query,
    },
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在 MongoDB 使用 Golang 实现条件附加》文章吧,也可关注golang学习网公众号了解相关技术文章。

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