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

Linda Hamilton
Release: 2024-11-04 20:23:02
Original
228 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template