How to update nested arrays in mongodb

I have an update function that creates a new array of campaigns inside a MongoDB document. Each campaign inside “campaigns” array has a “name” and another array called “leads”

This is how I’m creating it:

await users.updateMany(
      { email: },
      { $push: { campaigns: { name: campaignname, type, leads: [] } } }

Now what I want to do is “add” some data(array of objects) to the “leads” array with a specified campaign name.

So I essentially want to search for user, select the campaign inside the campaigns array by the “name” field and push the array of objects inside the “leads” array.

Please anyone help promptly.

Please provide sample input documents and expected result for some given data. It is much easier and faster for us to experiment with your real data compared to creating our own data based on your description.

1 Like