how to retrieve bson.Binary data

1,300 views
Skip to first unread message

Tom Lennon

unread,
Jan 7, 2013, 7:32:50 PM1/7/13
to mgo-...@googlegroups.com
I wrote a simple test program based on the example on the MGO web page and modified it to use some binary data. When I run this, binary data is written into the database but when the record is retrieved the binary data does not get unmarshalled into the struct. The name field is unmarshalled just fine. I am sure I am overlooking something obvious. I noted in the documentation that if the data does not fit the field in the struct then it is "silently skipped" and I thought that might have been the source of my problems but preallocating len and capacity of the byte array in the bson.Binary field did nothing. I would really appreciate it if someone could point out the proper tree for me to start barking up.

Here is the sample code
package main

import (
"fmt"
)

type Sample struct {
Name string
Bin bson.Binary
}

func main() {
session, err := mgo.Dial("xxxxxxxxxxxxxxxxx")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("test").C("samples")
err = c.Insert(&Sample{"CoreSample1", bson.Binary{0, []byte("Some random goop")}})
if err != nil {
panic(err)
}
result := Sample{}
err = c.Find(bson.M{"name": "CoreSample1"}).One(&result)
if err != nil {
panic(err)
}
fmt.Println(result)
}

Tom Lennon

unread,
Jan 7, 2013, 8:36:57 PM1/7/13
to mgo-...@googlegroups.com
I found my own tree to bark up - Thanks

The data goes out as bson.Binary and looks like bson.Binary in the database as in, it has a type and the binary data itself. The retrieved field, however, unmarshalls into a byte array. 

Gustavo Niemeyer

unread,
Jan 14, 2013, 7:02:40 AM1/14/13
to mgo-...@googlegroups.com
Hi Tom,
That's right. []byte is sent and received to the database as a bson
binary, so you can use that in place of the explicit bson.Binary in
most cases.


gustavo @ http://niemeyer.net
Reply all
Reply to author
Forward
0 new messages