2

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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
R2D2
  • 9,410
  • 2
  • 12
  • 28
  • Is this meet your requirement? [Demo](https://mongoplayground.net/p/4OkjwueY170) – Yong Shun Oct 12 '22 at 13:12
  • 1
    it seems I am missing something maybe due to version is 4.2 but not working :( – R2D2 Oct 12 '22 at 13:20
  • Sad to hear that. But anyway it's weird, I don't think it is due to version issue. The docs for version 4.2 shows [example](https://www.mongodb.com/docs/v4.2/reference/operator/update/positional-filtered/#update-nested-arrays-in-conjunction-with) for updating nested array elements. Fingers crossed. – Yong Shun Oct 12 '22 at 13:25
  • ah found why: https://mongoplayground.net/p/vVxiFUc7LV_ , please, advice it happen that not all nested elements are present in all documents and it is normal – R2D2 Oct 12 '22 at 13:33
  • Here you go. [Demo](https://mongoplayground.net/p/to1uMje3hb2). It's like spamming the `{ $exists: true }` – Yong Shun Oct 12 '22 at 13:47

1 Answers1

2

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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • This is a very nice solution! – nimrod serok Oct 12 '22 at 13:17
  • indeed I like it too but not working when there is not exisiting elements in the path ... :( , @Yong Shun , please , help with the fix and I will accept your answer. – R2D2 Oct 12 '22 at 13:36
  • 2
    How about [this](https://mongoplayground.net/p/hnLa_xmGvJa)? - just a small change – nimrod serok Oct 12 '22 at 13:47
  • 2
    Nice @nimrodserok, this works better in one line, rather than in my comment. – Yong Shun Oct 12 '22 at 13:49
  • one more similar question if somebody interested: https://stackoverflow.com/questions/74043251/double-nested-array-with-multiple-nested-documents-identify-wrong-value – R2D2 Oct 12 '22 at 14:05