Home > database >  MongoDB - update an object inside a multi dimensional numerical indexed array
MongoDB - update an object inside a multi dimensional numerical indexed array

Time:04-28

I am learming MongoDB (ver 5) [with Django (pymongo)] and facing a problem to update a multidimensional numerical array of objects.

I want to update an object value nested within a multi dimensional array.

Sample collection data:

[
  {
    "_id": {
      "$oid": "6269a7a2d9a928481c1ee94c"
    },
    "data": [
      [
        [
          {
            "id": "",
            "word": "arep 1"
          },
          {
            "id": "",
            "word": "arep 2"
          },
          {
            "id": "",
            "word": "arep 3"
          }
        ],
        [
          {
            "id": "",
            "word": "arep 4"
          },
          {
            "id": "",
            "word": "arep 5"
          },
          {
            "id": "",
            "word": "arep 6"
          }
        ],
        [],
        []
      ],
      
    ]
  }
]

I want to update the "id" field value to "some new id" where the relevant "word" is "arep 2". So far I have created an update query like:

db.collection.update({
  "_id": {
    "$oid": "6269a7a2d9a928481c1ee94c"
  },
  "data.$.$.$": {
    "word": "arep 2"
  }
},
{
  "$set": {
    "data.$[].$[].$[]": {
      "id": "some new id"
    }
  }
},
{
  "upsert": true
})

But the value is not getting set. What am I doing wrong?

mongo playground

Thank you for reading this far. Some more thanks beforehand for brainstorming on a solution.

CodePudding user response:

Query

  • arrayfilters to match the word= "arep 2"
  • for all members(2 nested levels)($[] means for all members), set the word(that satisfies the arrayFilter)($[w].word) to "hello"

Playmongo

update(
{"_id": {"$eq": 1}},
{"$set": {"data.$[].$[].$[w].word": "hello"}},
{"arrayFilters": [{"w.word": {"$eq": "arep 2"}}]})
  • Related