Select fields on Find function

I want to filter fields in a find query. For example, I have a collection called Users, where a field is an image in base64. I need to get all columns except image column.

I tried the next code, but Select not exist:
cur, err := collection.Find(context.TODO(), bson.D{{}}).Select(bson.M{"id": 1, "_id": 1, "title": 1, "description": 1, "date": 1, "formatteddate": 1})

Any help please?

Hi @Miguel_Rodriguez_Cre, welcome!

You can utilise mongo/options to specify query projection. Please see Project Fields To Return From Query for more information on query projection.

An example to omit a field foobar:

opts := options.Find().SetProjection(bson.D{{"foobar", 0}})
cursor, err := collection.Find(context.TODO(), bson.M{}, opts)

See also Collection.Find()

Regards,
Wan.

1 Like