Home  >  Article  >  Backend Development  >  How to Preserve Nested Structures When Storing Go Structs in MongoDB?

How to Preserve Nested Structures When Storing Go Structs in MongoDB?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 20:23:02183browse

How to Preserve Nested Structures When Storing Go Structs in MongoDB?

Storing Nested Structs with Mgo

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn