Mongo:投影不影响布尔值
时间:2024-03-17
浏览:450
作者:佚名
在使用 MongoDB 的投影功能时,作者发现布尔值字段不会被投影排除在外,即使其他字符串字段被成功排除。经过分析,作者发现这是由于结构体字段的默认值导致的。为了解决这个问题,作者建议将布尔值字段声明为指针类型,这样在投影后它们将被设置为 nil,从而实现排除投影的效果。
问题内容
我注意到,我可以将投影设置为不返回我的 username 或 userid 字符串,而不会出现问题。但是,当尝试不返回 deactivated 或 admin 布尔值时,即使其他字符串不会出现,它们仍然会出现?
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 <nil>}
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学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.30
11.30
11.30
11.30
11.30
11.30
11.30
11.30
热门专题
