Details
-
Bug
-
Resolution: Works as Designed
-
Major - P3
-
None
-
1.3.3
-
None
-
ubuntu 18.04
go 1.14
MongoDB server version 4.2.5
Description
Hi,
I've noticed a weird behavior when decoding result to bson.M
for some reason, all the field of the bson.M document are sorted when fetched from a collection. Not sure if the reordering happens during Find or Decode though
go code to reproduce the issue:
package main |
import ( |
"context" |
"fmt" |
"go.mongodb.org/mongo-driver/bson" |
"go.mongodb.org/mongo-driver/mongo" |
"go.mongodb.org/mongo-driver/mongo/options" |
)
|
func main() {
|
client, _ := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017")) |
doc := bson.M{
|
"b": 1, |
"a": 2, |
}
|
c := client.Database("test").Collection("collection") |
c.Drop(context.Background())
|
c.InsertOne(context.Background(), doc)
|
result := bson.M{}
|
cursor, _ := c.Find(context.Background(), bson.M{})
|
if cursor.Next(context.Background()) { |
cursor.Decode(result)
|
}
|
fmt.Printf("%+v", result) |
client.Disconnect(context.Background())
|
}
|
|
output:
map[_id:ObjectID("5eb498f45f45605b861334f4") a:2 b:1] |
expected behavior (mongo shell): the field order should not change
> use test
|
switched to db test
|
> db.collection.drop()
|
true
|
> db.test.insert({"b":1, "a":2}) |
WriteResult({ "nInserted" : 1 }) |
> db.test.find()
|
{ "_id" : ObjectId("5eb4993ff3c0910e14193d5b"), "b" : 1, "a" : 2 } |
the old mgo driver was not changing the field order
This was initially noticed here: mongoplayground.net/p/6--axoMYpDZ