Go Driver - strange behavior unmarshalling nested documents

I came upon a strange behavior of the Go driver.
Given the following document:

{
  foo: {
    "1": "bar"
  }
}

This document can be unmarshalled into the following struct:

type Foobar struct {
  Foo    map[int]any
}

But if the value of foo.1 is a nested document, that triggers an error:

{
  foo: {
    "1": {"nested": "bar"}
  }
}

Unmarshalling this document triggers the following error:

error decoding key foo.1: failed to unmarshal number key nested.

Changing the type of Foobar.Foo from map[int]any to map[string]any solves the problem and the error is not triggered.
This seems inconsistent, I don’t understand why only the nested document triggers an error on the key unmarshalling.
Should it not have been possible to unmarhal to map[int]any in the first place?

Hello @Yishai_Berg,

This is an expected behavior, that has been addressed in GODRIVER-2407.

BSON has no existing provisions for retaining application-runtime-specific type information. All maps are encoded as embedded documents. Therefore, when we unmarshal such data, the decoder uses its ancestor type.

You can specify DefaultDocumentM in this case. Here is an example to unmarshal your data properly.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.