Preserve map order while unmarshalling bson data to a Golang map

Viewed 81

Mongo driver used: https://pkg.go.dev/go.mongodb.org/mongo-driver

I have some data saved in the mongodb like below:

 {
        "title" : "elem_1_3_title",
        "list" : "elem_1_3_list"
 }

When I receive this data using mongodb driver then it sorts the map in the alphabetical order:


cursor, err := collection.Aggregate(context.TODO(), pipeline)
if err != nil {
    // handle err
}
pages := make([]map[string]interface{})
err = cursor.All(context.TODO(), &pages)
if err != nil {
    // handle err
}

output:

{
    "list" : "elem_1_3_list",
    "title" : "elem_1_3_title"
}

updated:

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"`
}

The data from database is received in this struct & sections field is the map which needs to be ordered.

NOTE: I can not define structs for this as I have a very long list of fields & some new fields can be added in the future.

Is there any possible way to receive the same order which is saved under mongodb ?

1 Answers

You might need an ordered map in order to preserve order.

See for instance elliotchance/orderedmap described in "An Ordered Map in Go".
Or wk8/go-ordered-map with Go 1.18 and parameter types.

In both instances, that would replace your make([]map[string]interface{})

om := orderedmap.New[string, string]()
Related