Search code examples
mongodbmongodb-querymongodb-update

MongoDB - Update the value of one field with the value of another nested field


I am trying to run a MongoDB query to update the value of one field with the value of another nested field. I have the following document:

{
  "name": "name",
  "address": "address",
  "times": 10,
  "snapshots": [
    {
      "dayTotal": 2,
      "dayHit": 2,
      "dayIndex": 2
    },
    {
      "dayTotal": 3,
      "dayHit": 3,
      "dayIndex": 3
    }
  ]
}

I am trying like this:

db.netGraphMetadataDTO.updateMany( 
    { },
    [{ $set: { times: "$snapshots.$[elem].dayTotal" } }],
    {   
        arrayFilters: [{"elem.dayIndex":{"$eq": 2}}],
        upsert: false,
        multi: true
    }
);

but got an error:

arrayFilters may not be specified for pipeline-syle updates


Solution

  • You can't use arrayFilters with aggregation pipeline for update query at the same time.

    Instead, what you need to do:

    1. Get the dayTotal field from the result 2.

    2. Take the first matched document from the result 3.

    3. Filter the document from snapshots array.

    db.netGraphMetadataDTO.updateMany({},
    [
      {
        $set: {
          times: {
            $getField: {
              field: "dayTotal",
              input: {
                $first: {
                  $filter: {
                    input: "$snapshots",
                    cond: {
                      $eq: [
                        "$$this.dayIndex",
                        2
                      ]
                    }
                  }
                }
              }
            }
          }
        }
      }
    ],
    {
      upsert: false,
      multi: true
    })
    

    Demo @ Mongo Playground