登录
首页 >  Golang >  Go问答

Mongo:投影不影响布尔值

来源:stackoverflow

时间:2024-03-17 18:39:25 450浏览 收藏

在使用 MongoDB 的投影功能时,作者发现布尔值字段不会被投影排除在外,即使其他字符串字段被成功排除。经过分析,作者发现这是由于结构体字段的默认值导致的。为了解决这个问题,作者建议将布尔值字段声明为指针类型,这样在投影后它们将被设置为 nil,从而实现排除投影的效果。

问题内容

我注意到,我可以将投影设置为不返回我的 usernameuserid 字符串,而不会出现问题。但是,当尝试不返回 deactivatedadmin 布尔值时,即使其他字符串不会出现,它们仍然会出现?

user := model.user{}
    filter := bson.d{
        {
            key:   "_id",
            value: userid,
        },
    }
    projection := bson.d{
        {
            key:   "password",
            value: 0,
        },
        {
            key:   "username",
            value: 0,
        },
        {
            key:   "_id",
            value: 0,
        },
        {
            key:   "deactivated",
            value: 0,
        },
        {
            key:   "admin",
            value: 0,
        },
    }
    options := options.findone().setprojection(projection)
    _ = userscol.findone(ctx, filter, options).decode(&user)

&{ false false [0xc00028d180] 0xc0002b0900 0xc0002bdce0 }

type User struct {
    ID           string          `json:"id" bson:"_id"`
    Admin        bool            `json:"admin"`
    Deactivated  bool            `json:"deactivated"`
    Username     string          `json:"username"`
    Password     string          `json:"password"`
    ...
}

正确答案


您看到的值是结构体字段的默认值。我建议您使用指向 user 字段的指针:

type User struct {
    ID           string           `json:"id" bson:"_id"`
    Admin        *bool            `json:"admin"`
    Deactivated  *bool            `json:"deactivated"`
    Username     string           `json:"username"`
    Password     string           `json:"password"`
    ...
}

在此示例中,值将为 nil

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Mongo:投影不影响布尔值》文章吧,也可关注golang学习网公众号了解相关技术文章。

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