How to store nested structs in MongoDB with mgo and retain a flattened structure?

Barbara Streisand
Release: 2024-11-07 00:53:02
Original
475 people have browsed it

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

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

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!

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