Search code examples
arraysmongodbcrud

Mongo Query to modify the existing field value with new value + array of objects


I want to update many documents based on the condition in MongoDB.

MODEL is the collection which has the document with below information.

    "info": [
      {
        "field1": "String1",
        "field2": "String2"
      },
      {
        "field1": "String1",
        "field2": "String_2"
      }
    ],
    "var": "x"

I need to update all the "String1" value of field1 with "STRING_NEW". I used the below query to update but not working as expected.

 db.model.updateMany(
         { "info.field1": { $exists: true } },
        [
            { "$set": { 
                "info": {
                    "$map": {
                        "input": "$info.field1",
                        "in": {
                            "$cond": [
                                { "$eq": ["$$this.field1", "String1"] }, 
                                 "STRING_NEW",
                                  $$this.field1
                            ]
                        }
                    }
                }
            } }
        ]
    )

Please have a look and suggest if anything is to be modified in the above query.


Solution

  • Solution 1

    With the update with aggregation pipeline, you should iterate the object in info array and update the iterated object by merging the current object with new field1 field via $mergeObjects.

    db.model.updateMany({
      "info.field1": "String1"
    },
    [
      {
        "$set": {
          "info": {
            "$map": {
              "input": "$info",
              "in": {
                "$cond": [
                  {
                    "$eq": [
                      "$$this.field1",
                      "String1"
                    ]
                  },
                  {
                    $mergeObjects: [
                      "$$this",
                      {
                        "field1": "STRING_NEW"
                      }
                    ]
                  },
                  "$$this"
                ]
              }
            }
          }
        }
      }
    ])
    

    Demo Solution 1 @ Mongo Playground


    Solution 2

    Can also work with $[<identifier>] positional filtered operator and arrayFilters.

    db.model.updateMany({
      "info.field1": "String1"
    },
    {
      "$set": {
        "info.$[info].field1": "STRING_NEW"
      }
    },
    {
      arrayFilters: [
        {
          "info.field1": "String1"
        }
      ]
    })
    

    Demo Solution 2 @ Mongo Playground