登录
首页 >  Golang >  Go问答

对Go中的MongoDB BSON地图字段进行禁用

来源:stackoverflow

时间:2024-02-27 17:18:21 289浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《对Go中的MongoDB BSON地图字段进行禁用》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我正在使用 "go.mongodb.org/mongo-driver/bson"

有没有办法能够禁用一个字段,但仍然是一个有效的 bson 映射?

publishFilter := bson.M{}

if publishedOnly {
    publishFilter = bson.M{"published": true}
}

pipeline := []bson.M{
    {"$sort": bson.M{"_id": -1}},
    {
        "$match": bson.M{
            "_id": bson.M{
                "$gt":  sinceObjectID,
                "$lte": maxObjectID,
            },
            publishFilter, // I want to control this to be nothing or `{"published": true}`
            // depending on `publishedOnly`
        },
    },
    {"$limit": query.Count},
}

此代码段绝对无法编译 地图文字中缺少键


解决方案


您无法“禁用”地图中的字段,但您可以有条件地构建 $match 文档:

matchDoc := bson.M{
    "_id": bson.M{
        "$gt":  sinceObjectID,
        "$lte": maxObjectID,
    },
}

if publishedOnly {
    matchDoc["published"] = true
}

pipeline := []bson.M{
    {"$sort": bson.M{"_id": -1}},
    {"$match": matchDoc},
    {"$limit": query.Count},
}

终于介绍完啦!小伙伴们,这篇关于《对Go中的MongoDB BSON地图字段进行禁用》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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