1

I have a document in mongodb with 2 level deep nested array of objects that I need to update, something like this.

{
  "id":12362,
  "onGoing":[
    {
      "id":14597,
      "offers":[
        {
          "id":56897,
          "status":"validated"
        },
        {
          "id":86127,
          "status":"validated"
        }
      ]
    },
    {
      "id":89451,
      "offers":[
        {
          "id":12235,
          "status":"validated"
        },
        {
          "id":56457,
          "status":"validated"
        }
      ]
    }
  ]
}

I would like to update all offers matching with their id.

I have tried to update like

db.repairJobs.update({
  "onGoing.offers":{
    $elemMatch:{
      _id:{
        $in:[
          '56897', '56457'
        ]
      }
    }
  }
},
{
  $set:{
    "ongoing.offers.$.status":"ACCEPTED"
  }
});  

But getting the error: cannot use the part (ongoing of ongoing.offers.0.status) to traverse the element ({ongoing: [ { _id: null, ...

Are there any ways to update, the solution need to be compatible with spring Data.

2 Answers 2

1

As far as I know there is no way to update documents two level deep in MongoDB. I stumbled upon this JIRA item. I don't think there's a way to use multiple $ operators in update operations.

https://jira.mongodb.org/browse/SERVER-831

I am not aware of any workarounds based on your current schema but I would recommend you to let's say, split your each of your onGoing arrays into different documents.

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

1 Comment

Thanks for the reply
0

You can use array filters to do this

Update Nested Arrays in Conjunction with $[]

as for your question, my solution is

db.repairJobs.update(
{},
{
  $set: {
    "onGoing.$[].offers.$[elem].status": "ACCEPTED"
  }
},
{ 
  arrayFilters: [{ "elem.id": {$in: [56897, 56457]} }],
  multi: true 
});

Comments

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.