skip to Main Content

https://mongoplayground.net/p/zIhLOT8YXLl

document schema:

{
  _id: ObjectId();
  array_property: [ {_id: ObjectId(), img_array: ["string", "string"] }, { }, ... ]
}

query:

 await user.updateOne(
            {
              _id: user_id,
              array_property: { $elemMatch: { _id: { $in: arrary_of_id } } },
            },
            {
              $push: {
                "array_property.$.img_array": {
                  $each: [new_img],
                },
              },
            }
          );

despite multiple elements of array_property matching the query, the $push will only happen to the first matching element. The rest are not modified.

How to fix this? The query is intended to update all matching elements of array_property.

2

Answers


  1. Chosen as BEST ANSWER

    use arrayFilters:

    db.collection.update({
      key: 1
    },
    {
      $set: {
        cheese: "farts"
      },
      $push: {
        "a.$[x].b": {
          $each: [
            4
          ]
        }
      }
    },
    {
      arrayFilters: [
        {
          "x.id": {
            $in: [
              1
            ]
          }
        }
      ]
    })
    

    https://mongoplayground.net/p/CwH6ZActsv_https://mongoplayground.net/p/CwH6ZActsv_


  2. Try using updateMany

    updateOone is doing exactly as it sounds, updating one document.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search