You're attempting to save a heavily nested Go struct to a MongoDB document. However, the nested structure gets flattened when you use json.Marshal or mgo.Collection.Upsert with a struct.
To preserve the nested structure in the database, utilize the bson:",inline" field tag in your Go struct definition. This tag instructs Mgo to treat the nested struct's fields as if they were direct fields of the outer struct.
For instance, consider the simplified example you mentioned:
<code class="go">type Square struct { Length int Width int } type Cube struct { Square `bson:",inline"` Depth int }</code>
In this case, the Cube struct will be stored in the database with the following JSON structure:
<code class="json">{ "Length": 2, "Width": 3, "Depth": 4 }</code>
This matches your desired output and preserves the nested structure.
The above is the detailed content of How to Preserve Nested Structures When Storing Go Structs in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!