How to specify fields in FindOne command in golang?

This is my actuall code:

type usernameOnly struct {
	username string `bson:"username"`
}
var user usernameOnly
		users.FindOne(ctx, bson.M{"username": "kotcich"}).SetProjection(bson.M{"username": 1}).Decode(&user)

But i’m getting this error:

users.FindOne(ctx, (bson.M literal)).SetProjection undefined (type *mongo.SingleResult has no field or method SetProjection)
I just want to do it simple. I’ve seen example in official doc
, but it’s too complicated.
Basic usage FindOne with golang from offical doc look like this:

var podcast bson.M
podcastsCollection.FindOne(ctx, bson.M{}).Decode(&podcast);

So… i don’t really unserstand, why i can’t just add SetProjection to FindOne like 1 query. Or i’m missing something?

Hello @shizzic_N_A, welcome to the MongoDB Community forum!

I tried something like this and this works:

A sample document in the collection:

{ "_id" : ObjectId("620effe71b12151a2477a14a"), "name" : "John" }

Golang code:

// Struct definition
type Gotest struct {
    Name string `bson:"name"`
}
// My func
var result Gotest
collection := client.Database("test").Collection("gotest")
filter := bson.D{{ "name", "John" }}
project := bson.D{{ "name", 1 }}
opts := options.FindOne().SetProjection(project)

err = collection.FindOne(context.TODO(), filter, opts).Decode(&result)

if err != nil {
    log.Fatal(err)
}

fmt.Printf("Found the document: %+v\n", result)

Reference: Collection.FindOne