2019-09-17 15:02
采纳率: 0%
浏览 342


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)
    打赏 评论

相关推荐 更多相似问题