_id as an object of three nodes

I am creating _id as an obect of three node _id:{a:1,b:1,c:1}, all are float64, and while inserting, I am using map[string]interface to write it as query, so maintaing order. But mongo keep making multiple documents. Mongo driver in golang doesn’t maintain order? and Primitive.M also doesn’t work

Hey @Aman_Saxena thanks for the question! In Go, map types are explicitly unordered (see more info here). As a result, creating a document from a map[string]interface{} or a primitive.M will not guarantee the order of the fields in the resulting document. Instead, use a struct or a bson.D to guarantee the order of fields in the resulting document.

Example using a struct:

type myID struct {
	A float64
	B float64
	C float64
}

type myDocument struct {
	ID myID `bson:"_id"`
	// Other fields.
}

func main() {
	var client mongo.Client
	coll := client.Database("test").Collection("test")
	doc := myDocument{
		ID: myID{A: 1, B: 1, C: 1},
	}
	coll.InsertOne(context.TODO(), doc)
}

Example using a bson.D:

func main() {
	var client mongo.Client
	coll := client.Database("test").Collection("test")
	doc := bson.D{
		{"_id", bson.D{
			{"a", float64(1)},
			{"b", float64(1)},
			{"c", float64(1)},
		}},
		// Other fields.
	}
	coll.InsertOne(context.TODO(), doc)	
}
1 Like

Thank you @Matt_Dale