Get embedded object values in an ordered map from MongoDb Go driver

462 Views Asked by At

GO version: 1.18.3

Mongodb version: 4.4

Mongodb driver used: go.mongodb.org/mongo-driver/bson

I want to receive an embedded object saved in the database in the form of a map with preserved order (order matters for me). For this I have used following package:

https://github.com/elliotchance/orderedmap

from the following reference:

Preserve map order while unmarshalling bson data to a Golang map

Now I have a struct below:

type PageResp struct {
    Id            int                               `json:"_id,omitempty" bson:"_id,omitempty"`
    Status        int                               `json:"status" bson:"status"`
    AddedSections []string                          `json:"added_sections" bson:"added_sections"`
    Sections        *orderedmap.OrderedMap            `json:"sections,omitempty" bson:"sections,omitempty"`
}

But Sections are empty by using type like this. I have tried it by defining type alias as well. Nothing is working.

After that I receive the data from mongodb in a temp variable with type bson.D then explicitly loop over this to build an ordered map. See the code below:

type PageResp struct {
    Id            int                               `json:"_id,omitempty" bson:"_id,omitempty"`
    Status        int                               `json:"status" bson:"status"`
    AddedSections []string                          `json:"added_sections" bson:"added_sections"`
    SectionsTemp2   *orderedmap.OrderedMap            `json:"sections_temp2,omitempty" bson:"sections_temp2,omitempty"`
    SectionsTemp    bson.D                            `json:"sections_temp,omitempty" bson:"sections_temp,omitempty"`
}

// function to convert bson.D to ordered map
func test(sections bson.D) *orderedmap.OrderedMap {
    newSections := orderedmap.NewOrderedMap()
    for _, section := range sections {
        childMap := orderedmap.NewOrderedMap()
        for _, v := range section.Value.(bson.D) {
            childMap.Set(v.Key, v.Value)
        }
        // fmt.Println("childMap", childMap)
        newSections.Set(section.Key, *childMap)
    }
    // fmt.Println("newSections", newSections)
    return newSections
}

But this method is returning values like:

result: &{map[123:0xc0000125d0 foo:0xc000012570 qux:0xc0000125a0] 0xc000012540}

But it should return values like:

result: [["foo","bar"],["qux",1.23],[123,true]]

It shows that this package is also not maintaining the order. Also if some other method for ordered map exists, please write to me.

Thanks!

0

There are 0 best solutions below