Home > Software engineering >  Mongo DB - Difficulty Updating Multiple within a given document structure
Mongo DB - Difficulty Updating Multiple within a given document structure

Time:04-21

I've got an application with a Mongo database that has documents stored with a structure something like this:

{
    "_id" : ...,
    "order_no": 12345,
    "results": [
        {
            "a": "customer",
            "b": "name",
            "result": "John Doe"
        },
        {
            "a": "order_info",
            "b": "date",
            "result": "2022-04-19T00:00:00.000Z"
        },
        {
            "a": "order_type",
            "b": "type",
            "result": "Standard"
        }
    ]
}

So say I need to change the company name to 'John Doe Ltd', I'm struggling to update all documents belonging to customer John Doe so that the customer name reflects this change.

I've tried

collection.updateMany( { "results.a": "customer", "results.b": "name", "results.result": "John Doe" }, [{ $set: { "results.a": "customer", "results.b": "name", "results.result": "John Doe Ltd" } }] )

but I'm getting an error..."Cannot create field 'a' in element..."

I'm hoping that someone can point me in the right direction. Thanks in advance.

CodePudding user response:

db.collection.update({
  "results.a": "customer",
  "results.b": "name",
  "results.result": "John Doe"
},
{
  "$set": {
    "results.$.a": "customer",
    "results.$.b": "name",
    "results.$.result": "John Doe Ltd"
  }
})

For updating specific objects in an array, you would have to use the positional $ operator which will increment the matched document.

But do note that it updates only the first matched object in the array. If more than one object match for a particular query only the first will be updated.

Here is the code for reference: https://mongoplayground.net/p/o4gFzyQ8HTn

  • Related