Liam Clarke
Liam Clarke

Reputation: 263

How to return only a selection of results from mongodb with the golang mongo-driver

I would like to create an array of objects but only with a filtered list of key-values.

    collection, err := driver.GetDBCollection()

    cur, err := collection.Find(context.Background(), bson.D{{}})
    if err != nil {
        log.Fatal(err)
    }

    var results []primitive.M
    for cur.Next(context.Background()) {
        var result bson.M
        e := cur.Decode(&result)
        if e != nil {
            log.Fatal(e)
        }
        results = append(results, result)

    }

Lets say my data in mongodb looks like this:

[
    {
        "_id": "123456",
        "username": "username1",
        "password": "hashedPassword",
        "token": "theToken"
    },
    {
        "_id": "123456",
        "username": "username2",
        "password": "hashedPassword",
        "token": "theToken"
    },
    {
        "_id": "123456",
        "username": "username3",
        "password": "hashedPassword",
        "token": "theToken"
    },
    {
        "_id": "123456",
        "username": "username4",
        "password": "hashedPassword",
        "token": "theToken"
    }
]

What i currently have above will return all of that but if i didn't want to expose some fields, how would i return all results from just selected keys, for example not including the password and token, like this:

[
    {
        "_id": "123456",
        "username": "username1"
    },
    {
        "_id": "123456",
        "username": "username2"
    },
    {
        "_id": "123456",
        "username": "username3"
    },
    {
        "_id": "123456",
        "username": "username4"
    }
]

ref: https://godoc.org/go.mongodb.org/mongo-driver/mongo

Upvotes: 0

Views: 1468

Answers (1)

Liam Clarke
Liam Clarke

Reputation: 263

For anyone else who cannot find this, here is the solution, its not very well documented:

    opts := options.Find().SetProjection(bson.M{
        "_id":       1,
        "username":  1,
    })
    cur, err := collection.Find(context.Background(), bson.D{{}}, opts)

Upvotes: 3

Related Questions