db.collection.find({}, {your_key:1, _id:0})

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


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为同一投影创建过滤器?


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


蝴蝶不菲
浏览 67回答 1
1回答

侃侃尔雅

这样的事情应该工作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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go