I want to get the entire list_atttributes
field from my mongo document:
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 }
}
}
]
I tried to write it like this:
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)
}
But the cursor returns 0 results here.
How do I create a bson.M
filter for the same projection?
I am using the official mongodb drive for go.
CodePudding user response:
Something like this should work
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
}