Home > database >  MongoDB - Update nested array with many nested objects
MongoDB - Update nested array with many nested objects

Time:10-13

I need to update the dateP in the following structure with "2022-01-02", but it seems not an easy task:

{
  "_id": ObjectId("5c05984246a0201286d4b57a"),
  "_a": [
    {
      "_p": {
        "s": {
          "a": {}
        }
      }
    },
    {
      "_onlineStore": {}
    },
    {
      "_p": {
        "s": {
          "a": {
            "t": [
              {
                c: 4
              },
              {
                "dateP": "20200-09-20",
                "l": "English",
                "size": "XXL"
              },
              {
                c: 1
              }
            ]
          },
          c: {
            t: 2
          }
        }
      }
    }
  ]
}

playground

I attempted with arrayFilters, but without success as not all elements exist in all documents and some documents are pretty empty. Please advice.

MongoDB 4.2 community

CodePudding user response:

Believe that you need the filtered positional operator for _a array to check whether the document has the _p field or not.

db.collection.update({},
{
  $set: {
    "_a.$[a]._p.s.a.t.$[x].dateP": "2022-01-02"
  }
},
{
  arrayFilters: [
    {
      "a._p": {
        $exists: true
      }
    },
    {
      "x.dateP": "20200-09-20"
    }
  ]
})

Demo @ Mongo Playground

  • Related