如何使用golang mongo驱动程序仅从mongodb返回选择的结果

如何使用golang mongo驱动程序仅从mongodb返回选择的结果,mongodb,go,bson,Mongodb,Go,Bson,我想创建一个对象数组,但只使用筛选过的键值列表 collection,err:=driver.GetDBCollection() cur,err:=collection.Find(context.Background(),bson.D{}) 如果出错!=零{ log.Fatal(错误) } var results[]primitive.M 对于cur.Next(context.Background()){ var结果bson.M e:=当前解码(&结果) 如果e!=nil{ 日志。致命(e) }

我想创建一个对象数组,但只使用筛选过的键值列表

collection,err:=driver.GetDBCollection()
cur,err:=collection.Find(context.Background(),bson.D{})
如果出错!=零{
log.Fatal(错误)
}
var results[]primitive.M
对于cur.Next(context.Background()){
var结果bson.M
e:=当前解码(&结果)
如果e!=nil{
日志。致命(e)
}
结果=追加(结果,结果)
}
假设我在mongodb中的数据如下所示:

[
    {
        "_id": "123456",
        "username": "username1",
        "password": "hashedPassword",
        "token": "theToken"
    },
    {
        "_id": "123456",
        "username": "username2",
        "password": "hashedPassword",
        "token": "theToken"
    },
    {
        "_id": "123456",
        "username": "username3",
        "password": "hashedPassword",
        "token": "theToken"
    },
    {
        "_id": "123456",
        "username": "username4",
        "password": "hashedPassword",
        "token": "theToken"
    }
]
[
    {
        "_id": "123456",
        "username": "username1"
    },
    {
        "_id": "123456",
        "username": "username2"
    },
    {
        "_id": "123456",
        "username": "username3"
    },
    {
        "_id": "123456",
        "username": "username4"
    }
]
我目前拥有的上述内容将返回所有这些内容,但如果我不想公开某些字段,我将如何返回仅选定密钥的所有结果,例如,不包括密码和令牌,如下所示:

[
    {
        "_id": "123456",
        "username": "username1",
        "password": "hashedPassword",
        "token": "theToken"
    },
    {
        "_id": "123456",
        "username": "username2",
        "password": "hashedPassword",
        "token": "theToken"
    },
    {
        "_id": "123456",
        "username": "username3",
        "password": "hashedPassword",
        "token": "theToken"
    },
    {
        "_id": "123456",
        "username": "username4",
        "password": "hashedPassword",
        "token": "theToken"
    }
]
[
    {
        "_id": "123456",
        "username": "username1"
    },
    {
        "_id": "123456",
        "username": "username2"
    },
    {
        "_id": "123456",
        "username": "username3"
    },
    {
        "_id": "123456",
        "username": "username4"
    }
]
参考:

对于任何其他找不到这一点的人,这里有一个解决方案,它没有很好的文档记录:

opts:=options.Find().SetProjection(bson.M{
“_id”:1,
“用户名”:1,
})
cur,err:=collection.Find(context.Background(),bson.D{{},opts)

您考虑过“投影”吗?