登录
首页 >  Golang >  Go问答

使用 bson.M 过滤器检索 db.collection 的数据

来源:stackoverflow

时间:2024-02-18 12:45:24 157浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《使用 bson.M 过滤器检索 db.collection 的数据》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我想从我的 mongo 文档中获取整个 list_atttributes 字段:

db.config.find({},{list_attributes:1, _id:0});
[
{
    list_attributes: {
    '0': { field: 'lastname', field_key: 'lastname', datatype: 'text' },
    '1': { field: 'firstname', field_key: 'firstname', datatype: 'text' },
    '2': { field: 'sms', datatype: 'text' },
    '3': {
        field: 'double_opt-in',
        datatype: 'category',
        order: 1,
        catattrib: { '1': 'yes', '2': 'no' }
    },
    '4': { field: 'opt_in', datatype: 'boolean', order: 2 },
    '5': { field: 'test_number', datatype: 'float', order: 3 },
    '6': { field: 'test_date', datatype: 'date', order: 4 }
    }
}
]

我尝试这样写:

filter := options.Find().SetProjection(bson.M{"list_attributes": 1})

// Pass the filter to Find() to return a MongoDB cursor
cursor, err := col.Find(ctx, filter)
if err != nil {
    log.Fatal("col.Find ERROR:", err)
}

但是光标在这里返回 0 个结果。

如何为同一投影创建 bson.m 过滤器?

我正在使用 go 的官方 mongodb 驱动。


正确答案


这样的东西应该有效

import (
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func find(ctx context.Context) error {
    // ...
    cursor, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"list_attributes": 1}))
    if err != nil {
        return err
    }
    // ...
    return nil
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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