Home > Article > Backend Development > How to store nested structs in MongoDB with mgo and retain a flattened structure?
Storing Nested Structs in MongoDB with Mgo
Nested structs in Go can pose a challenge when transitioning to MongoDB documents. When using json.Marshal and writing to standard output, nested structs are flattened. However, when using mgo.Upsert, the nested structure is maintained.
To retain the flattened structure in MongoDB, employ the bson:",inline" tag for the nested struct. This tag indicates that the nested struct's fields should be treated as if they were part of the outer struct.
For instance, consider the following code:
<code class="go">type Square struct { Length int Width int } type Cube struct { Square `bson:",inline"` Depth int }</code>
Here, the Square struct is embedded into the Cube struct with the bson:",inline" tag. When using mgo.Upsert with this struct, the resulting document will have the following format:
{ "Length":2, "Width":3, "Depth":4 }
This inline tag approach allows you to maintain the desired flattened structure in MongoDB without modifying the original struct definition or resorting to manual flattening techniques.
The above is the detailed content of How to store nested structs in MongoDB with mgo and retain a flattened structure?. For more information, please follow other related articles on the PHP Chinese website!