如何使用正式的mongo-go-driver驱动程序过滤mongo文档中的字段 [英] How to filter fields from a mongo document with the official mongo-go-driver

查看:530
本文介绍了如何使用正式的mongo-go-driver驱动程序过滤mongo文档中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用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驱动程序的发展,可以使用简单的

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,并使用结构标签像这样将其映射到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 作为投影,您不需要自己的struct类型.例如.以下内容相同:

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆