'update an array element in mongodb
I am trying to update an array element inside a document without changing whole array.
Array elements look like this
Suppose i have to only update index 1 element's value. For that i have:
_idof the documentindex
1's value ("optionalImages-624476a7bd4d2bfe6bf86e9a-1-1650025533684.jpeg")to be updated value ("optionalImages-624476a7bd4d2bfe6bf86e9a-1-1650025534589.jpeg").
I think it can be updated by mongodb's arrayfilters but i don't get the documentation correctly.
Your help will be highly appreciated.
Solution 1:[1]
Query1
- arrayFilters using
$[m]inside the path to specify the member value that we want to change - m is the member with value 20, and we set it to 100
(instead of 20 and 100, put your "....jpg" strings)
update(
{"_id": {"$eq": 1}},
{"$set": {"ar.$[m]": 100}},
{"arrayFilters": [{"m": {"$eq": 20}}])
Query2
- pipeline update >= MongoDB 4.2
- uses map on the array to
- find the member with value 20, and replaces it with 100
update(
{"_id": {"$eq": 1}},
[{"$set":
{"ar":
{"$map":
{"input": "$ar",
"in": {"$cond": [{"$eq": ["$$this", 20]}, 100, "$$this"]}}}}}])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

