2 / 2
Jul 2024

i have a data that is

[{ "massName": "PI", "month":7, "member": [ { "name": "shamim", "meal": [ ], "pyment":[ { "07-07-2024":500 }, { "13-07-2024":500 } ] }, { "name": "imran", "meal": [ ], "pyment":[ { "07-07-2024":300 }, { "13-07-2024":500 } ] }, { "name": "hasibul", "meal": [ ], "pyment":[ { "07-07-2024":500 }, { "13-07-2024":700 } ] } ], "bazar":[ { "name":"shamim", "date": "07-07-2024", "amount":750 }, { "name":"imran", "date": "07-07-2024", "amount":560 } ] } ]

now i want to replace meal 2.5 to 4 for the member name shamim and date 07-07-2024. i try to solve it using many way but i failed. there’s some way
1.
db.massDetails.updateOne( { "member.name": "shamim", "member.meal.07-07-2024": { $exists: true } }, { $set: { "member.$.meal.'07-07-2024'": 3 } } )
2.
db.massDetails.updateOne( { "member.name": "shamim", "member.meal.07-07-2024": { $exists: true } }, { $set: { "member.$.meal": {'07-07-2024':3}} } )
please anyone give me the solution

Hello @MD_Shamim_Reza1, Welcome,

You have to use arrayFilters to update nested array, follow the points corrected in your query,

  • match, use $elemMatch to satisfy both conditions in the same element
  • arrayFilters, create an identifier m and check the same condition that date exists or not
  • update, use the $[m] identifier so it will match and update the value on the specific date.
db.massDetails.updateOne({ "member": { "$elemMatch": { "name": "shamim", "meal.07-07-2024": { "$exists": true } } } }, { "$set": { "member.$.meal.$[m].07-07-2024": 4 } }, { "arrayFilters": [{ "m.07-07-2024": { "$exists": true } }] })