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 updateacName of a specific ID? Let's say, I want to updateacName ofid 2. How can I do that?

Yong Shun's user avatar
Yong Shun
54.3k6 gold badges37 silver badges65 bronze badges
askedAug 16, 2022 at 1:58
Rashel's user avatar

1 Answer1

4

Solution 1: Without arrayFilters

  1. Use$elemMatch to find the existence ofid: 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

answeredAug 16, 2022 at 2:30
Yong Shun's user avatar
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 thisdemo. While would suggest try to attempt before asking. And would recommend to create a new question for the new requirement. Thanks.

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.