Mongodb 如何使用官方mongo go驱动程序从mongo文档中筛选字段

Mongodb 如何使用官方mongo go驱动程序从mongo文档中筛选字段,mongodb,go,struct,projection,mongo-go,Mongodb,Go,Struct,Projection,Mongo Go,如何使用mongo go驱动程序筛选字段。 用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{

如何使用mongo go驱动程序筛选字段。 用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)

最后,我想抑制字段“\u id”。但是文档没有改变。

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

options.FindOne().SetProjection(bson.M{"_id": 0})
type fields struct {
    ID int `bson:"_id"`
}
原始(旧)答案如下


它不适用于您的原因是字段
字段。_id
未报告,因此,没有其他包可以访问它(只有声明的包)

必须使用导出的字段名(以大写字母开头),例如
ID
,并使用将其映射到MongoDB
\u ID
字段,如下所示:

options.FindOne().SetProjection(bson.M{"_id": 0})
type fields struct {
    ID int `bson:"_id"`
}
现在使用投影执行查询:

projection := fields{
    ID: 0,
}
result := staCon.collection.FindOne(
    nil, filter, options.FindOne().SetProjection(projection)).Decode(s)
请注意,您也可以使用a作为投影,您不需要自己的结构类型。例如,以下情况也一样:

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

这太复杂了,是我真的需要定义一个struct?,还是我可以使用bson.M?@LoboNokeweNgewe是的,你也可以使用
bson.M
值。由于这个答案是创建的,mongo go驱动程序改进了很多。对于多个投影字段,使用
bson.D{{{{u id],0},{“name”,1}