1

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
  • With a map the order is not guaranted. I recommand you to define a struct as huge is it. Commented May 25, 2022 at 6:28

1 Answer 1

0

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]()
Sign up to request clarification or add additional context in comments.

9 Comments

What if I wanted to use this ordered map type for a field type in a struct? How can I do that ? Meaning how can I use this for map[string]map[string]interface{} ?
@Amandeepkaur in your case, string would be the key, and the rest being the type of the value. I would define a type alias for the value type.
wk8/go-ordered-map is not woking, it says cant find package. you mean for map[string]map[string]interface{}, it would be m := orderedmap.NewOrderedMap[string, any]() ?
@Amandeepkaur I would need to test it (but I am on my phone right now)
I have updated the post, could you please check that If its possible ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.