Update nested arrays with upsert

Hi guys,

I used to prepare another approach for a different data model, but try to use something of this sort:

db.sample.update({books: {$elemMatch: {Category: "<FILTER_FIELD_KEY>", BookInfos: "<FILTER_FIELD_VALUE>"}}}, 
                   [{$addFields: {input: {$zip: {inputs: ["$books", [{Category: "<TARGET_FIELD_KEY>", BooksInfos: {...} }]]}}}}, 
                    {$set: {books: {"$arrayElemAt": ["$input", 0]}}}, 
                    {$project: {input : 0}}
                   ]
                  );

The Idea is to zip the array with the nee element and get a sort of upsert to an array.

Let me know if you need a more specific examples.

Thanks
Pavel

1 Like