2

This is my function from mongodb-go-driver:

func MongodbFindOne(key, value string) bson.M {
    var result bson.M
    opts := options.FindOne().SetShowRecordID(false)
    _ = Collection.FindOne(context.TODO(), bson.M{key: value}, opts).Decode(&result)
    return result
}

The function works very good but i get _id field in the result. I know the mongodb query to exclude a field from query result, But i don't know how to use it with FindOne() function:

From tutorialspoint:

db.removeIdDemo.find({},{_id:0});

From mongodb query result without field name

db.collection.find({},{_id:0, t_number:1}).toArray().map(function(ele) {return ele.t_number} );

From remove _id from mongo result (nodejs):

app.get('/itesms', function(req, res) {   items.find({}, { _id: 0 }).toArray(function (err, array) {
    res.send(array);   }) });

1 Answer 1

5

To exclude fields from the result, use a projection. Use FindOneOptions.SetProjection() to set the projection.

To specifically exclude the _id field:

err = c.FindOne(ctx,
    bson.M{key: value},
    options.FindOne().SetProjection(bson.M{"_id": 0}),
).Decode(&result)
Sign up to request clarification or add additional context in comments.

2 Comments

When I exclude _id, Im still getting id as 000000.... in the result struct. So how to remove that?
@Poujhit If your Go type (struct) holds an objectID, it will be initialized to its zero value. If you don't want that, remove the objectID field from your Go struct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.