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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里