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?
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)