Search code examples
node.jsmongodbmongoosemultipartform-datamulter

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

enter image description here

Suppose i have to only update index 1 element's value. For that i have:

  1. _id of the document

  2. index 1's value ("optionalImages-624476a7bd4d2bfe6bf86e9a-1-1650025533684.jpeg")

  3. 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

  • 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)

    Playmongo

    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

    Playmongo

    update(
    {"_id": {"$eq": 1}},
    [{"$set": 
       {"ar": 
         {"$map": 
           {"input": "$ar",
            "in": {"$cond": [{"$eq": ["$$this", 20]}, 100, "$$this"]}}}}}])