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

5
  • Is this meet your requirement? Demo Commented Oct 12, 2022 at 13:12
  • 1
    it seems I am missing something maybe due to version is 4.2 but not working :( Commented Oct 12, 2022 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 for updating nested array elements. Fingers crossed. Commented Oct 12, 2022 at 13:25
  • ah found why: mongoplayground.net/p/vVxiFUc7LV_ , please, advice it happen that not all nested elements are present in all documents and it is normal Commented Oct 12, 2022 at 13:33
  • Here you go. Demo. It's like spamming the { $exists: true } 😂 Commented Oct 12, 2022 at 13:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

This is a very nice solution!
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.
How about this? - just a small change
Nice @nimrodserok, this works better in one line, rather than in my comment.
one more similar question if somebody interested: stackoverflow.com/questions/74043251/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.