Exploring the depths of nested arrays and updating with mongoose

Here is a simplified diagram of a document in my Model:

{
    ar1: [
        {
            b: {
                ar2: [{ _id: 1, value: 2 }],
            },
        },
        {
            b: {
                ar2: [{ _id: 2, value: 2 }],
            },
        },
        {
            b: {
                ar2: [{ _id: 1, value: 5 }],
            },
        },
    ];
}

Now I'm looking to update all elements of ar2 that have an _id equal to 1 so the result would be:

{
    ar1: [
        {
            b: {
                ar2: [{ _id: 1, value: 3 }],
            },
        },
        {
            b: {
                ar2: [{ _id: 2, value: 2 }],
            },
        },
        {
            b: {
                ar2: [{ _id: 1, value: 3 }],
            },
        },
    ];
}

The code snippet below does not achieve this:

Model.updateMany({
    'ar1.b.ar2._id' : 1
},{
    'ar1.$[].b.ar2.$[].value' : 2
});

Any recommendations on how to approach this?

The goal is to target specific elements within the nested array and update their values based on a query.

Answer №1

To achieve this task, you can utilize the combination of $[] together with $[<identifier>]:

Model.update(
  {}, 
  { $set: { "ar1.$[].b.ar2.$[el].value": 3 } },  
  { arrayFilters: [ { "el._id": 1 } ] } 
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Aligning divs, prevent duplicate HTML within multiple divs

Currently, I am attempting to troubleshoot a jsfiddle issue. The main problem lies in my desire for the first two divs (with class="fbox") to be aligned next to each other on the same level. Furthermore, I am looking to enable dragging the image into the ...

Displaying lines of an XML file without the accompanying tags

Currently, I am parsing an XML file line by line: var lines = $(xml).text().split("\n"); $.each(lines, function(n, elem) { console.log(elem); }); However, the code above only displays the content within the tags, not the actual XML lines. I have ...

Stop the browser url from changing in VueJs when the location is updated

My Vue.js application involves making REST API calls to the backend, with defined routers and components for navigation. However, as I navigate through the application, I am encountering a situation where the URL in the browser displays the specific route ...

Spotlight the flaw in the card's backbone using JS

What's the most effective method for emphasizing an error card view in backbone? Initially, I render 10 cards as UI where users input details in each card. Upon clicking submit, I validate all the details by parsing through collection->models. Curr ...

Issue with using Bootstrap-select in conjunction with HTMX partials

I'm currently experimenting with using Bootstrap-select alongside HTMX partials in my Django project. When a specific element is modified, HTMX returns a partial HTML that includes only a dropdown menu, like this: <select id="myDropdown" ...

Displaying items using a filter function in ng-repeat

I am facing an issue with using a filter on my ng-repeat that involves a function with a parameter passed in, but for some reason, the filter is not working as expected. The function I am using for the filter compares two arrays to find any matching eleme ...

Retrieve a specific key value from a dictionary within a Flask function by employing JavaScript

I'm currently working on a feature where a user can input something in a search field, and upon submitting, the script should send a request to a Flask function using JavaScript. The response data should then be loaded accordingly. However, I've ...

Is there a way to generate bootstrap divs by parsing csv text?

As I am working on a Bootstrap 3 image gallery, I have noticed that there are multiple recurring divs with a similar structure as shown below: <figure class="col-1 picture-item" data-groups='["groupA"]' data-date-created="2018" data-title=" ...

Guide on invoking a method from a class in a different file

Seeking a solution to a task involves calling a function from a different file within a class. Here's what I am trying to achieve: file1 export class Example { constructor() { ... } myCustomFunction = () => { ... } } file2 impor ...

Updating two separate <DIV> elements with a single AJAX request

Can two different targeted DIVs be updated simultaneously using a single ajax call? Consider the index.html code snippet below: <script> xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.rea ...

What is the process for combining two geometries or meshes in three.js?

I am working with two types of geometries: a line-based square 2D geometry and an icon image. My goal is to center and place the icons inside the designated region of the 2D rectangle. Here is the code snippet I have written: var combined = new THREE.Ge ...

Unpacking key-value pairs from a JSON array in PHP and restructuring the data

Looking for suggestions on how to transform the JSON structure shown below: $jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"}, {"Level":"399.2023%","Product":"Coffee","Temperature":"34"}, {"Level":"109.2023%","Product ...

Bringing in two JavaScript files with identical names

Recently, I encountered a challenging situation. I am working with material-ui and nextjs, both of which have a module called Link that is essential for my project. import { Link } from '@material-ui/core'; However, this setup is causing compil ...

Guide on displaying console.log in mobile simulator while using Angular2

Interested in debugging JavaScript on mobile devices, particularly Android and iPhone. Seeking a code snippet or library that can display console.log messages on the screen of a phone emulator. Ideally looking for a solution that works with angular2 and i ...

Using res.sendfile in a Node Express server and sending additional data along with the file

Can a Node.JS application redirect to an HTML file using the res.sendFile method from express and include JSON data in the process? ...

I must determine whether the contents of an array exceed zero

THE SUMMARY: I have three value numbers for an array. If the total addition of the array's elements is greater than 0, I need to display "el funcionamiento no es infinito", otherwise "es infinito". It seems that it's not working because I belie ...

Uncovering data from keys stored within arrays containing numerous key-value pairs using dart/flutter

In the following array, there are key-value pairs that I am analyzing for a specific output: If 'global' is set to true, I need to print the value of the 'title' key within the same object. If 'global' is false, then I should ...

Memory Exhausted: MongoDB and JavaScript running out of memory

Dealing with a massive amount of data in the telemetry table is proving to be a challenge. I keep encountering the dreaded "JavaScript heap out of memory" error. How can I tackle this issue? const connectionUrl = `mongodb://${userName}:${pwd}@${host}:${ ...

The C# [WebMethod] will not trigger if the Content-Type "application/Json" is missing

After creating a C# WebMethod, I was able to successfully call it using Ajax, angular, and Postman when adding the header Content-Type: 'application/Json'. Here is an example of the HTTP request that worked: $http({ url: 'default.aspx/G ...

Even though I am utilizing the `.then()` method, my asynchronous function continues to return a status of

Here is my code attempting to retrieve response data. const fetchRobots = () => { axios.get("https://jsonplaceholder.typicode.com/users").then((response) => { return response.data; }); }; let robotsData = fetchRobots(); console.log(robots ...