Problem with any type in Golang

Answers:

  1. Why does this happen?
    MongoDB BSON documents preserve the order of fields, where Go map values do not. While it’s possible to unmarshal into a map[string]any, it would not preserve the original document order. There is no native Go type that can represent any MongoDB BSON document and preserve the order, so the Go Driver uses bson.D as the default BSON document representation when unmarshaling.
  2. What was the reasoning behind this decision?
    See the answer to #1.
  3. Is there a way to control the type conversion?
    You can set BSONOptions.DefaultDocumentM to true, which will cause the Go Driver to always unmarshal BSON documents into a bson.M value instead of a bson.D when there’s no other type information. For example:
opts := options.Client().SetBSONOptions(&options.BSONOptions{
	DefaultDocumentM: true,
})
client, err := mongo.Connect(context.TODO(), opts)
// ...

P.S. If you’re unmarshaling BSON directly, you can call Decoder.DefaultDocumentM to cause a bson.Decoder to unmarshal BSON documents into bson.M instead of bson.D .

2 Likes