How to marshal/unmarshal bson in to a struct

2,271 views
Skip to first unread message

iamth...@gmail.com

unread,
Jul 29, 2018, 12:43:13 AM7/29/18
to mongodb-go-driver
I am new to mongodb-go-driver. But i am stuck.

cursor, e := collection.Find(context.Background(), bson.NewDocument(bson.EC.String("name", id)))

for cursor.Next(context.Background()) {

e := bson.NewDocument()
cursor.Decode(e)

b, _ := e.MarshalBSON()
err := bson.Unmarshal(b, m[id])
}

My map is like this : m   map[string]Language

and Language is :
type Language struct {
ID         string   `json:"id" bson:"_id"`                   // is this wrong?
Name       string   `json:"name" bson:"name"`
Vowels     []string `json:"vowels" bson:"vowels"`
Consonants []string `json:"consonants" bson:"consonants"`
}

What am I doing wrong?

iamth...@gmail.com

unread,
Jul 30, 2018, 9:19:49 AM7/30/18
to mongodb-go-driver
I have found the answer. Sharing for those who are interested.

cursor, e := collection.Find(context.Background(), bson.NewDocument(bson.EC.String("name", id)))

for cursor.Next(context.Background()) {
l := Language{}
cursor.Decode(&l)

m[id] = l
}

The above works.

iamth...@gmail.com

unread,
Jul 30, 2018, 9:21:39 AM7/30/18
to mongodb-go-driver
Forgot to add the correct definition of Language struct.

type Language struct {
ID         objectid.ObjectID `json:"id" bson:"_id"`
Name       string            `json:"name" bson:"name"`
Vowels     []string          `json:"vowels" bson:"vowels"`
Consonants []string          `json:"consonants" bson:"consonants"`
}

Reply all
Reply to author
Forward
0 new messages