Mongodb update a value in array of object of array

i have a problem that i cannot resolved by myself. i have a data in mongo db and i want to update specific value i show the code and images what i want is to update the specific object (the min propetry) how i can update it?

await user.findOneAndUpdate(
      {
        name: "sss",
        id: "test1",
        decibelHistory: {
          $elemMatch: { config: { min: 10 } },
        },
      },
      {
        $set: { "config.$.min": 1 },
      }
    );

Document

{
  "_id": {
    "$oid": "638b39c2d96a4ac3ebb33c6b"
  },
  "name": "sss",
  "password": "sss",
  "decibelHistory": [
    {
      "id": "test1",
      "config": [
        {
          "max": 90,
          "min": 10,
          "avg": 35
        }
      ]
    }
  ],
  "timeLapse": 1200,
  "__v": 0
}

Hello @Lior_aharon ,

Welcome to The MongoDB Community forums! :wave:

I notice you haven’t had a response to this topic yet - were you able to find a solution?
If not, you can try using below query to update the values of field min.

db.collection.updateOne(
    {"name" :  "sss", "decibelHistory.id": "test1"},
    {$set: {
        'decibelHistory.$[].config.$[x].min': 999
    }},
    {arrayFilters: [
        {"x.min": 10}
    ]}
)

Below is the explanation of the query.

  • db.collection.updateOne() : Updates a single document within the collection based on the filter.
  • The $set operator replaces the value of a field with the specified value.
  • The filtered positional operator $[<identifier>] identifies the array elements that match the arrayFilters conditions for an update operation. In the example above, it was used in conjunction with the arrayFilters option to update all elements that match the arrayFilters conditions.
    For more details, please see Update Nested Arrays in Conjunction with $

Note that the code example above seems to work correctly with the example document you posted, thus you may need to modify the example code to suit your use case better

Let me know if you have any more questions. Happy to help! :slight_smile:

Regards,
Tarun

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.