从 golang 中的 mongodb 查询结果中删除一个字段

remove a field from mongodb query result in golang

这是我在 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
}

该函数运行良好,但我在结果中得到 _id 字段。我知道 mongodb 查询从查询​​结果中排除一个字段,但我不知道如何将它与 FindOne() 函数一起使用:

来自tutorialspoint

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

来自mongodb query result without field name

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

来自 remove _id from mongo result (nodejs):

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

要从结果中排除字段,请使用投影。使用FindOneOptions.SetProjection()设置投影。

具体排除_id字段:

err = c.FindOne(ctx,
    bson.M{key: value},
    options.FindOne().SetProjection(bson.M{"_id": 0}),
).Decode(&result)