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); }) });
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)