问题描述
这是我从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()
函数一起使用它:
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)