1

This is my collection structure in MongoDB:

{
  _id: id,
  name: name,
  loans: [
    [{id: 1, acName: "ABC"}],
    [{id: 2, acName: "DEF"}],
    [{id: 3, acName: "GHI"}]
  ]
}

How can I update acName of a specific ID? Let's say, I want to update acName of id 2. How can I do that?

1 Answer 1

4

Solution 1: Without arrayFilters

  1. Use $elemMatch to find the existence of id: 2 in nested arrays.

  2. With all positional operator ($[]) to update the respective document field.

db.collection.update({
  "loans": {
    $elemMatch: {
      $elemMatch: {
        id: 2
      }
    }
  }
},
{
  $set: {
    "loans.$.$[].acName": "<NEW VALUE>"
  }
})

Demo Solution 1 @ MongoPlayground


Solution 2: With arrayFilters

  1. Use $elemMatch to find the existence of id: 2 in nested arrays.

  2. With filtered positional operator ($[<identifier>]) and arrayFilters to update the respective document field.

db.collection.update({
  "loans": {
    $elemMatch: {
      $elemMatch: {
        id: 2
      }
    }
  }
},
{
  $set: {
    "loans.$.$[loan].acName": "<NEW VALUE>"
  }
},
{
  arrayFilters: [
    {
      "loan.id": 2
    }
  ]
})

Demo Solution 2 @ MongoPlayground

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

4 Comments

Great. Thanks. It works. Could you please do me another favor? Let's say, my loans is like this: loans: [ [{id: 1, acName: "ABC"}, {id: 4, acName: "KKK}], [{id: 2, acName: "DEF"}, {id: 5}, acName: "MMM"], [{id: 3, acName: "GHI", {id: 6, acName: "NNN"}}] ] How would I be able to change acname of id 2 ?
Solution 2 is preferred based on your new data. Demo
It worked as well. Highly appreciated. Please please don't mind. What if I need to update all acName together depnding on category? loans: [ [{id: 1, acName: "ABC", category: "good"}, {id: 4, acName: "KKK", category: "bad"}], [{id: 2, acName: "DEF", category: "good"}, {id: 5, acName: "MMM", category: "good"}], [{id: 3, acName: "GHI", category: "bad"}, {id: 6, acName: "NNN", category: "bad"}}] ] I will not ask question again. I apologize for repetitive questions.
You may look for this demo. While would suggest try to attempt before asking. And would recommend to create a new question for the new requirement. Thanks.

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.