如何使用官方 mongo-go-driver 从 mongo 文档中过滤字段

How to filter fields from a mongo document with the official mongo-go-driver

如何使用 mongo-go-driver 过滤字段。 尝试使用 findopt.Projection 但没有成功。

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”。但是文件没有改变。

编辑: 随着 mongo-go 驱动程序的发展,可以使用如下简单的 bson.M 指定投影:

options.FindOne().SetProjection(bson.M{"_id": 0})

原始(旧)答案如下。


它对您不起作用的原因是字段 fields._id 未导出,因此,没有其他包可以访问它(只有声明包)。

您必须使用导出的字段名称(后者以大写字母开头),例如ID,并使用 struct tags 将其映射到 MongoDB _id 字段,如下所示:

type fields struct {
    ID int `bson:"_id"`
}

现在使用投影执行查询:

projection := fields{
    ID: 0,
}
result := staCon.collection.FindOne(
    nil, filter, options.FindOne().SetProjection(projection)).Decode(s)

请注意,您也可以使用 bson.Document 作为投影,您不需要自己的结构类型。例如。以下做同样的事情:

projection := bson.NewDocument(
    bson.EC.Int32("_id", 0),
)
result := staCon.collection.FindOne(
    nil, filter, options.FindOne().SetProjection(projection)).Decode(s)