我注意到,我可以将投影设置为不返回usernameuserID个字符串,而不会出现问题.但是,当try 不返回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 <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"`
    ...
}

推荐答案

您看到的值是struct字段的默认值.我建议您使用指向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.

Mongodb相关问答推荐

我无法将文档发送到我的MongoDB集合,因为它告诉我使文档无效

在Mongoose中对嵌套文档设置时间戳,但不对父文档设置时间戳

如何替换mongodb中的动态键?

用Golang减go mongodb中的两个字段

创建索引需要很长时间

mongodb中集合的最大大小是多少

为什么 MongoDB 配置服务器必须只有一个或三个?

Spring Boot MongoDB 连接问题

无法使用机器 ip 连接到 mongodb

在 Heroku 上使用 Node 读取、写入和存储 JSON

Node.js 和 MongoDB,重用 DB 对象

在 Nodejs 中找不到模块

什么是 mongodb 中的admin数据库?

适用于 Windows 10 64 位的 MongoDB 下载

带有 jQ​​uery Ajax/JSON 前端的 MongoDB 或 CouchDB 中间件

如果我在 MongoDB 上使用 LINQ,为什么会失go 性能?

用于嵌入式集合的 MongoDB 首选模式.文档与数组

PyMongo 中的警告消息:count is deprecated

如何在 Mongoid 中引用嵌入的文档?

MissingSchemaError:Schema hasn't been registered for model