Hi Team,
I am trying to update a nested array field using UpdateOne with aggregation pipeline but it leads to unexpected outcome. Please note that I could’ve using UpdateOne with Array Filters but doesn’t generate correct audits in case of multiple matches.
In the below document, I want to set isPrimary as true for all facilitators in 0th index of acquirers list. But the given query unexpectedly sets “0” as a key for each acquirer.
Existing Document:
{ "_id": 1, "acquirers": [ { "type": "COMPANY", "isPrimary": true, "id": "a", "facilitators": [ { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": true, "id": "a" }, { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": true, "id": "a" }, { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": true, "id": "a" } ] }, { "type": "COMPANY", "isPrimary": true, "id": "a", "facilitators": [ { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": true, "id": "a" }, { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": true, "id": "a" }, { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": true, "id": "a" } ] } ] }
`
Query:
`
db.acquisitionV3.updateOne( { "_id": 1, "acquirers.0.facilitators.id": "a", "acquirers.0.facilitators.type": "COMPANY" }, [ { $set: { "acquirers.0.facilitators": { $map: { input: "$acquirers.0.facilitators", as: "facilitator", in: { $cond: [ { $and: [ { $eq: ["$facilitator.id", "a"] }, { $eq: ["$facilitator.type", "COMPANY"] } ] }, { $mergeObjects: [ "$facilitator", { isPrimary: false } ] }, "$facilitator" ] } } } } } ] )
`
Updated Document:
`
{ "_id": 1, "acquirers": [ { "0": { "facilitators": [] }, "type": "COMPANY", "isPrimary": true, "id": "a", "facilitators": [ { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": true, "id": "a" }, { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": false, "id": "a" }, { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": false, "id": "a" } ] }, { "0": { "facilitators": [] }, "type": "COMPANY", "isPrimary": true, "id": "a", "facilitators": [ { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": true, "id": "a" }, { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": false, "id": "a" }, { "notablePeople": [ "a" ], "type": "COMPANY", "isPrimary": false, "id": "a" } ] } ] }
`
Thanks