【问题标题】:How to return only a selection of results from mongodb with the golang mongo-driver如何使用 golang mongo-driver 仅返回来自 mongodb 的部分结果
【发布时间】:2020-02-14 00:39:51
【问题描述】:

我想创建一个对象数组,但只能使用过滤后的键值列表。

    collection, err := driver.GetDBCollection()

    cur, err := collection.Find(context.Background(), bson.D{{}})
    if err != nil {
        log.Fatal(err)
    }

    var results []primitive.M
    for cur.Next(context.Background()) {
        var result bson.M
        e := cur.Decode(&result)
        if e != nil {
            log.Fatal(e)
        }
        results = append(results, result)

    }

假设我在 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"
    }
]

参考: https://godoc.org/go.mongodb.org/mongo-driver/mongo

【问题讨论】:

标签: mongodb go bson


【解决方案1】:

对于找不到这个的其他人,这里是解决方案,它的文档不是很好:

    opts := options.Find().SetProjection(bson.M{
        "_id":       1,
        "username":  1,
    })
    cur, err := collection.Find(context.Background(), bson.D{{}}, opts)

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 2020-07-19
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多