douyi2798 2018-11-02 14:08
浏览 245
已采纳

如何使用官方的mongo-go-driver驱动程序过滤mongo文档中的字段

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)

In the end, I want to suppress the field "_id". But the documents didn't change.

  • 写回答

1条回答 默认 最新

  • duanchou6534 2018-11-05 13:54
    关注

    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).

    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)
    

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵