如何使用官方 mongo-go-driver 从 mongo 文档中过滤字段 [英] How to filter fields from a mongo document with the official mongo-go-driver
问题描述
如何使用 mongo-go-driver 过滤字段.用 findopt.Projection 试过了,但没有成功.
How can I filter fields with the mongo-go-driver. Tried it with findopt.Projection but no success.
type fields struct {
_id int16
}
s := bson.NewDocument()
filter := bson.NewDocument(bson.EC.ObjectID("_id", starterId))
var opts []findopt.One
opts = append(opts, findopt.Projection(fields{
_id: 0,
}))
staCon.collection.FindOne(nil, filter, opts...).Decode(s)
最后,我想取消字段_id".但文件没有改变.
In the end, I want to suppress the field "_id". But the documents didn't change.
推荐答案
随着 mongo-go 驱动程序的发展,可以使用简单的 bson.M
像这样:
As the mongo-go driver evolved, it is possible to specify a projection using a simple bson.M
like this:
options.FindOne().SetProjection(bson.M{"_id": 0})
原始(旧)答案如下.
它对您不起作用的原因是字段 fields._id
未导出,因此,没有其他包可以访问它(只有声明包).
The reason why it doesn't work for you is because the field fields._id
is unexported, and as such, no other package can access it (only the declaring package).
您必须使用导出的字段名称(以大写字母开头),例如ID
,并使用 struct标签将其映射到 MongoDB _id
字段,如下所示:
You must use a field name that is exported (starts with an uppercase latter), e.g. ID
, and use struct tags to map it to the MongoDB _id
field like this:
type fields struct {
ID int `bson:"_id"`
}
现在使用投影执行查询:
And now to perform a query using a projection:
projection := fields{
ID: 0,
}
result := staCon.collection.FindOne(
nil, filter, options.FindOne().SetProjection(projection)).Decode(s)
请注意,您也可以使用 bson.Document
作为投影,不需要自己的结构体类型.例如.以下内容相同:
Note that you may also use a bson.Document
as the projection, you don't need your own struct type. E.g. the following does the same:
projection := bson.NewDocument(
bson.EC.Int32("_id", 0),
)
result := staCon.collection.FindOne(
nil, filter, options.FindOne().SetProjection(projection)).Decode(s)
这篇关于如何使用官方 mongo-go-driver 从 mongo 文档中过滤字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!