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

Mary-Kate Olsen
Release: 2024-11-04 18:21:02
Original
464 people have browsed it

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!