使用Gobson / Mgo解组BSON数据

I am receiving different BSON documents, an example seen here:

{ "group" : { "id": ObjectId("11a123456bc345d452d32c0b5"), "name": "SomeName" }, "count1": 6, "count2": 33, "totalCount": 39 }

I am trying to use mgo/gobson to unmarshal this data into a map[string]interface{}, but keep getting an error. The unmarshalling code is

var record map[string]interface{}

err := bson.Unmarshal(data, &record)

This resulted in a error saying the document was corrupted. Looking into the code I saw that it expected the length of the byte array to be the first few bytes so I added code similar to what is found in the tests.

rec := make([]byte, len(data)+6)
binary.LittleEndian.PutUint32(rec, uint32(len(rec)))
copy(rec[4:], data)

This got me past the corrupt document error, but now I am getting

Unknown element kind (0x7B)

What am I doing wrong that I can't easily unmarshal the above BSON document into a map? Is there a problem with the BSON document itself? I am not the creator of the BSON document, but am able to provide feedback to them if necessary.

2016/08/24 18:27
  • mongodb
  • 点赞
  • 收藏
  • 回答