An unexpected error occurs in specific condition when trying to update a document with a somehow basic $set command.
If you try to $set an object property with an object containing inner property starting with $ an error message reject the request.
The issue only occurs when the query is run as an aggregate query.
Here is a short script to reproduce the issue:
package test
import (
"context"
"fmt"
"testing"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func TestBsonIssue(t *testing.T) {
ctx := context.Background()
clientOpts := options.Client().ApplyURI("mongodb://127.0.0.1/dev?retryWrites=true&w=majority")
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
panic(fmt.Sprintf("failed to connect to mongo server: %s", err))
}
err = client.Ping(ctx, nil)
if err != nil {
panic(fmt.Sprintf("failed to ping mongo server: %s", err))
}
devDb := client.Database("dev")
usersCol := devDb.Collection("Users")
filter := bson.D{{"_id", primitive.NewObjectID()}}
update := bson.A{
bson.D{{"$set", bson.D{
{"profile", bson.D{
{"fieldName", "whatever"},
{"$fieldName2", "someting"},
}},
}}},
}
updateOptions := options.Update().SetUpsert(true)
_, err = usersCol.UpdateOne(ctx, filter, update, updateOptions)
if err != nil {
t.Fatalf("failed to update user: %s", err)
}
}
The error:
failed to update user: write exception: write errors:
[Invalid $set :: caused by :: an expression specification must contain exactly one field,
the name of the expression.
Found 2 fields in { fieldName: "whatever", $$fieldName2: "someting" },
while parsing object { profile: { fieldName: "whatever", $$fieldName2: "someting" } }]