Update specific element value in sub-sub array and not all subarray elements

Hi all, I’m having a problem trying to update a value inside a sub-sub array. The element URLPDF is inside the contratos array and contratos is inside the report array. So my react query is:

updateOne(
                { "report.contratos.NumContrato": `${param[1]}` },
                {
                    $set: {
                        "report.$.contratos.URLPDF": {
                            $cond: {
                                if: {
                                    $eq: ["$report.$.contratos.NumContrato", `${param[1]}`]
                                },
                                then: `${param[2]}`,
                                else: null
                            }
                        }
                    }
                }
)

I’m trying to use cond so only one specific element of the subarray is updated and not all the elements. the query is returning an error: unhandledRejection:

MongoServerError: Cannot create field 'URLPDF' in element

If I only leave:

updateOne(
   { "report.contratos.NumContrato": `${param[1]}` },
   {
       $set: {  "report.$.contratos.URLPDF": `${param[1]}`  }
   }
)

Then all the 10 elements in the subarray are updated with the new value and I don’t want that, I just want to update the one matching the initial seach condition. I haven’t found much about updating in nested array having subarrays.

Please can somebody point me to the right direction.

Thanks

Hi @Alejandro_Chavero ,

Yes, you have a syntax called arrayFilters specifically for this scenario:

updateOne(
   { "report.contratos.NumContrato": `${param[1]}` },
   { $set: { "report.$[].conrators.$[NumContrato].URLPDF": `${param[2]}`} },
   { arrayFilters: [ { "conrators.NumContrato": `${param[1]}`}, ] }
)

Now I don’t have a sample document or Have O fully tested the code, but it should be similar.

Thanks
Pavel

thanks for the help Pavel, I just tweak your response a little bit and it worked like charm, instead of putting NumContrato in the brackets I put an “n” and in the filter part “n.NumContrato” and it worked.

updateOne(
                { "report.contratos.NumContrato": `${param[1]}` },
                { $set: { "report.$[].contratos.$[n].URLPDF": `${param[2]}` } },
                { arrayFilters: [{ "n.NumContrato": `${param[1]}` }] }
            );

Thanks again

1 Like

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