doukang7858 2019-09-17 15:02 采纳率: 0%
浏览 407
已采纳

使用golang从mongo获取一片json字符串

I am trying to get a slice of json text from mongo using the below code in golang

var a []string
err := col..Find(nil).Select(bson.M{"_id": 0}).All(&a)

I get the error Unsupported document type for unmarshalling: string

May I know the right way to do this?

  • 写回答

1条回答 默认 最新

  • doumi7861 2019-09-17 15:09
    关注

    When you select all but _id, the return will be a document containing only the remaining fields. You can do:

    type fieldDoc struct {
      Field string `bson:"name"`
    }
    var a []fieldDoc
    err := col.Find(nil).Select(bson.M{"_id": 0}).All(&a)
    

    If you don't know the underlying structure:

    var a []bson.M
    err := col.Find(nil).Select(bson.M{"_id": 0}).All(&a)
    

    That should give you the documents encoded as bson objects. That is a map[string]interface{}, so you should be able to marshal it to JSON if you want json output:

    jsonDocs, err:=json.Marshal(a)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity从3D升级到urp管线,打包ab包后,材质全部变紫色
  • ¥50 comsol温度场仿真无法模拟微米级激光光斑
  • ¥15 上传图片时提交的存储类型
  • ¥15 Ubuntu开机显示器只显示kernel,是没操作系统(相关搜索:显卡驱动)
  • ¥15 VB.NET如何绘制倾斜的椭圆
  • ¥15 arbotix没有/cmd_vel话题
  • ¥20 找能定制Python脚本的
  • ¥15 odoo17的分包重新供应路线如何设置?可从销售订单中实时直接触发采购订单或相关单据
  • ¥15 用C语言怎么判断字符串的输入是否符合设定?
  • ¥15 通信专业本科生论文选这两个哪个方向好研究呀