cannot transform type bson.Raw to a BSON Document: length read exceeds number of bytes available. length=4 bytes=1667457633

1,513 views
Skip to first unread message

sammy Ma

unread,
Oct 23, 2019, 9:08:23 AM10/23/19
to mongodb-go-driver
Hi, can I insert any bytes to mongodb?

Just like this code:
if resp, err := collection.InsertOne(context.TODO(), []byte("abcc")); err != nil {
       log
.Fatal(err)
} else {
       log
.Printf("%#v", resp)
}


But it returns error:
cannot transform type bson.Raw to a BSON Document: length read exceeds number of bytes available. length=4 bytes=1667457633

If my code shown below, it works.
key := RandStringRunes(4)
user
:=&User {
    ID
: key,
   
Name: "sammy",
    age
: 26,
}
val
, err := bson.Marshal(user)
if err != nil {
    log
.Fatal(err)
}

if resp, err := collection.InsertOne(context.TODO(), val); err != nil {
    log
.Fatal(err)
} else {
    log
.Printf("%#v", resp)
}



My project is going to use mongodb instead of leveldb, but I have encountered some difficulties in interface adaptation. 

Thank you in advance for your help.

Tao Liu

unread,
Oct 24, 2019, 6:48:25 AM10/24/19
to mongodb-go-driver
You should use BSON to insert document. See example.

Tim Fogarty

unread,
Oct 24, 2019, 9:56:36 AM10/24/19
to mongodb-go-driver
Hi Sammy,

Tao Liu is correct, the trick here is to insert a BSON document with your bytes as a field. I responded to your question on the blog post, I'm going to copy my response below so it's visible on the mailing list too:

You're trying to insert a string of bytes into a collection. But in MongoDB a collection is made up of JSON-like documents. So you need to insert a document that has your string of bytes as a value. You can read this to learn more about how MongoDB stores data as documents: https://docs.mongodb.com/manual/core/document/

So instead of inserting
 
[]byte("abcc")

insert
 
bson.M{"my_data": []byte("abcd")}

instead.

Here's a sample program that inserts this document into the database, then finds the document and prints it back to the console: https://gist.github.com/tfogo/1b37303e87c63f02bf34d2472171b167

Binary data is stored as a Binary type in BSON documents in the database. When you get documents back from the Go driver, Binary fields will have the primitive.Binary type. You can learn more about this type here: https://godoc.org/go.mongodb.org/mongo-driver/bson/primitive#Binary

Best,
Tim

sammy Ma

unread,
Oct 24, 2019, 10:32:52 AM10/24/19
to mongodb-go-driver
I have understanding BSON through reading MongoDB manual. Thank you so mush!

在 2019年10月24日星期四 UTC+8下午6:48:25,Tao Liu写道:

sammy Ma

unread,
Oct 24, 2019, 10:34:05 AM10/24/19
to mongodb-go-driver
Thanks for your patience. I will continue to learn the principles of mongodb.

在 2019年10月24日星期四 UTC+8下午9:56:36,Tim Fogarty写道:
Reply all
Reply to author
Forward
0 new messages