【问题标题】:remove a field from mongodb query result in golang从golang中的mongodb查询结果中删除一个字段
【发布时间】:2020-09-30 21:02:25
【问题描述】:

这是我的 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);   }) });

【问题讨论】:

    标签: json mongodb go bson mongo-go-driver


    【解决方案1】:

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

    要明确排除_id 字段:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-17
      • 2021-09-11
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 2021-04-01
      相关资源
      最近更新 更多