0
votes

I have a mongo document that contains an array of clients. I want to be able to update a clients name by their userid. I have code below so far. When I run it it get multiple write error. There is only one document with that _id in my database. How can I fix my code?

{

    "_id" : "999999999_9_clients",

    "clients" : [

        {

            "name" : "Joe",
            "age" : 7,
            "time" : "1563249601.932",
            "userid" : "6b528591-ad78-4b8b-9484-350853edcd44"

        },{

            "name" : "Mark",
            "age" : 17,
            "time" : "1563249601.932",
            "userid" : "7b528591-ad78-4b8b-9484-350853edcd44"
        }

    ],

}

Code:

key :="999999999_9_clients"

 

                filter := bson.M{"_id": key, "clients.userid": "6b528591-ad78-4b8b-9484-350853edcd44"}

                update := bson.M{

                                "$set": bson.M{

                                                "clients.name": "Sam",
                                 },

                }

                _, err := collection.UpdateOne(ctx, filter, update)

               

                if err != nil {

                             return err
                  }

 
1

1 Answers

1
votes

You are missing positional operaror

update := bson.M{
      "$set": bson.M{
             "clients.$.name": "Sam",
       },
}

Note the dollar sign in the update.

It is same across the Languages.

You are ignoring changeInfo but you could use that after update in Go.