Moa
Moa

Reputation: 153

In MongoDB, how to Update an Array in an Object in a Document

My Document looks like this in MongoDB:

  {
    "_id": {
        "$oid": "6099d057b769cc513025fd54"
    },
    "key_name": "I_CAN_MATCH",
    "object_1": {
        "sub_object_array_1": [{
            "a": "TZNNI",
            "b": "R"
        }],
        "sub_object_array_2": [{
            "c": "SDLYA",
            "d": "N"
        }, {
            "c": "KTSMQ",
            "d": "N"
        }],
        "sub_object_array_3": [{
            "e": "KYCT0",
            "f": "F"
        }, {
            "e": "KYCT1",
            "f": "N"
        }, {
            "e": "KYCT2",
            "f": "F"
        }, {
            "e": "KYCT3",
            "f": "E"
        }],
    },
    "object_2": {
      "sub_object_4": { "and": "so on ..." }
    },
    "object_array_1": [{
            "g": "KYCT0",
            "h": "F"
        }, {
            "g": "KYCT1",
            "h": "N"
        }, {
            "g": "KYCT2",
            "h": "F"
        }, {
            "g": "KYCT3",
            "h": "E"
        }]
  }

My question is how to Update Array sub_object_array_3 where f = "F" to f = "U"?

The following does not work for me:

  await db_model.updateMany( 
    { key_name: "I_CAN_MATCH" },
    { $set: { "object_1.sub_object_array_3.$[array_element].f": "U" } },
    { arrayFilters: [ { "array_element.f": "F" } ] } );

But the following does! So I understand how the syntax works in this scenario.

  await db_model.updateMany( 
    { key_name: "I_CAN_MATCH" },
    { $set: { "object_array_1.$[array_element].h": "U" } },
    { arrayFilters: [ { "array_element.h": "F" } ] } );

I just don't know what I'm missing in the $set command when the Array is inside an Object first.

I have searched, but every search word I use points me to arrays in arrays, which is not the case here. Is anyone able to help me?

Thanks in advance!

Upvotes: 1

Views: 318

Answers (1)

Error - https://mongoplayground.net/p/Cvfc6oNyhrH

fail to run update: multiple write errors: [{write errors: [{Error parsing array filter :: caused by :: The top-level field name must be an alphanumeric string beginning with a lowercase letter, found 'array_element'}]}, {<nil>}]

Solution :-

Change array_element to arrayElement or anything without _

Note:- it should be alphanumeric

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

The must begin with a lowercase letter and contain only alphanumeric characters.


Demo - https://mongoplayground.net/p/GJku1bFaj3m

db.collection.update({
  key_name: "I_CAN_MATCH"
},
{
  $set: {
    "object_1.sub_object_array_3.$[arrayElement].f": "U"
  }
},
{
  arrayFilters: [
    { "arrayElement.f": "F" }
  ]
})

Upvotes: 3

Related Questions