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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)