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

使用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 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示