Home  >  Article  >  Backend Development  >  How do I store nested Go structs with mgo while maintaining their structure in MongoDB?

How do I store nested Go structs with mgo while maintaining their structure in MongoDB?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 18:21:02465browse

How do I store nested Go structs with mgo while maintaining their structure in MongoDB?

Storing Nested Structs with mgo

When attempting to store a nested Go struct as a MongoDB document using mgo, users may encounter issues with the flattened structure. While the json.Marshal function can produce the desired flat structure, it stores the data as binary when upserted into MongoDB.

To maintain the nested structure during upserting, mgo provides the bson:",inline" field tag. This tag inlines the nested struct, causing its fields to be treated as part of the outer struct. For instance, consider the following simplified nested struct:

<code class="go">type Square struct {
    Length int 
    Width int
}

type Cube struct {
    Square
    Depth int
}</code>

By adding the bson:",inline" tag to the Square field, the struct is defined as follows:

<code class="go">type Cube struct {
    Square `bson:",inline"`
    Depth  int
}</code>

When upserted into MongoDB using mgo, the data will now have the desired flat structure:

<code class="json">{
     "Length":2,
     "Width":3,
     "Depth":4
}</code>

This approach allows users to maintain the readability and structure of their Go code while successfully storing nested structs in MongoDB.

The above is the detailed content of How do I store nested Go structs with mgo while maintaining their structure 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