diff --git a/bson/bson_test.go b/bson/bson_test.go index e2c1bf9e8b..6c004b1df0 100644 --- a/bson/bson_test.go +++ b/bson/bson_test.go @@ -19,6 +19,7 @@ import ( "go.mongodb.org/mongo-driver/bson/bsoncodec" "go.mongodb.org/mongo-driver/bson/bsonoptions" "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/internal/assert" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) @@ -226,11 +227,20 @@ func TestMapCodec(t *testing.T) { } func TestExtJSONEscapeKey(t *testing.T) { - doc := D{{Key: "\\usb#", Value: int32(1)}} + doc := D{ + { + Key: "\\usb#", + Value: int32(1), + }, + { + Key: "regex", + Value: primitive.Regex{Pattern: "ab\\\\\\\"ab", Options: "\""}, + }, + } b, err := MarshalExtJSON(&doc, false, false) noerr(t, err) - want := "{\"\\\\usb#\":1}" + want := `{"\\usb#":1,"regex":{"$regularExpression":{"pattern":"ab\\\\\\\"ab","options":"\""}}}` if diff := cmp.Diff(want, string(b)); diff != "" { t.Errorf("Marshaled documents do not match. got %v, want %v", string(b), want) } diff --git a/bson/bsonrw/extjson_writer.go b/bson/bsonrw/extjson_writer.go index 57781ff9f3..86a293570f 100644 --- a/bson/bsonrw/extjson_writer.go +++ b/bson/bsonrw/extjson_writer.go @@ -468,12 +468,13 @@ func (ejvw *extJSONValueWriter) WriteRegex(pattern string, options string) error return err } + options = sortStringAlphebeticAscending(options) var buf bytes.Buffer buf.WriteString(`{"$regularExpression":{"pattern":`) writeStringWithEscapes(pattern, &buf, ejvw.escapeHTML) - buf.WriteString(`,"options":"`) - buf.WriteString(sortStringAlphebeticAscending(options)) - buf.WriteString(`"}},`) + buf.WriteString(`,"options":`) + writeStringWithEscapes(options, &buf, ejvw.escapeHTML) + buf.WriteString(`}},`) ejvw.buf = append(ejvw.buf, buf.Bytes()...)