-1

I have a map, which I create from a slice of strings. I then want to marshal this into bson format, to insert into mongodb as an index. However, because of how maps are created in Golang, I get a different ordering of the index each time (sometimes its abc, othertimes its bac, cba...).

How can I ensure that the marshalled index created is always in the same order?

fields := ["a", "b", "c"] 

compoundIndex := make(map[string]int)
for _, field := range fields {
    compoundIndex[field] = 1
}
data, err := bson.Marshal(compoundIndex)
fmt.Println(string(data)) // This output is always in a different order than the desired abc
testing495
  • 212
  • 2
  • 12

1 Answers1

2

Use an ordered representation of a document, bson.D:

var compoundIndex bson.D
for _, field := range fields {
    compoundIndex = append(compoundIndex, bson.E{Key: field, Value: 1})
}
data, err := bson.Marshal(compoundIndex)
fmt.Println(string(data)) // The elements are always printed in the same order.

Run an example on the Playground.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • is there a typo? should it be append(compoundIndex, bson.D instead of append(compoundIndex, bson.E (change E to D)? Thanks fo answering my question :) – testing495 May 20 '21 at 15:13
  • 1
    @testing495 it is not a typo. `bson.D` is a `[]E`, an ordered list of `E`ntries. – Adrian May 20 '21 at 15:16
  • Interesting, I get "E not declared by package bsoncompilerUndeclaredImportedName " when I use that – testing495 May 20 '21 at 15:19
  • @testing495 The answer assumes that `bson` is a recent version of the package [go.mongodb.org/mongo-driver/bson](https://pkg.go.dev/go.mongodb.org/mongo-driver@v1.5.2/bson). Which package are you using for bson? – Charlie Tumahai May 20 '21 at 15:21
  • ah Im using go.mongodb.org/mongo-driver v1.4.6 – testing495 May 20 '21 at 15:23
  • Version 1.4.6 has type [E](https://pkg.go.dev/go.mongodb.org/mongo-driver@v1.4.6/bson#E). – Charlie Tumahai May 20 '21 at 15:24