Looking for assistance grasping the concept of using a for loop in MongoDB's aggregate method

This code snippet is designed to maintain the order of an array (var list) when utilizing mongoDb's $in clause effectively.

Although, I must admit that the logic behind it is not entirely clear to me.

I can see that it's iterating in reverse to preserve the order, but why is ref being assigned to list at i - 1, rather than i?

It's a bit challenging for someone like me with basic javascript knowledge, but it's a good exercise to test my current skill level.

If someone could kindly walk me through the process step-by-step, I would greatly appreciate it.

var list = [ 4, 2, 8 ];

var stack = [];

for (var i = list.length - 1; i > 0; i--) {

    var rec = {
        "$cond": [
            { "$eq": [ "$_id", list[i-1] ] },
            i
        ]
    };

    if ( stack.length == 0 ) {
        rec["$cond"].push( i+1 );
    } else {
        var lval = stack.pop();
        rec["$cond"].push( lval );
    }

    stack.push( rec );

}

var pipeline = [
    { "$match": { "_id": { "$in": list } }},
    { "$project": { "weight": stack[0] }},
    { "$sort": { "weight": 1 } }
];

db.collection.aggregate( pipeline );

Answer №1

Query:

what is the reason for assigning ref to the list at i - 1 instead of i?

Consider the example below

var arr = [x, y, z, m, p, q];

console.log(arr.length); //Output: 6
console.log(arr.indexOf('x'));//Output: 0

If you want to retrieve q from the array, you should do

var index = arr[arr.length-1];
console.log(index); //Output: q

I hope this explanation clarifies your doubt.

Try running the code snippet below:

var arr = ['x', 'y', 'z', 'm', 'n', 'o'];
console.log(arr.length);
console.log(arr.indexOf('x'));

var len = arr.length;
console.log(arr[len-1]);
console.log(arr[len]);

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

Sequential tests in the browser, not parallel

Currently, I am utilizing multiCapabilities for setting up multiple browsers. Is there a method to ensure that they run consecutively instead of concurrently? ...

Enhancing Numbers with JavaScript

What I'm Looking for: I have 5 counters on my webpage, each starting at 0 and counting upwards to different set values at varying speeds. For example, if I input the values of 10, 25, 1500, 400, and 500 in my variables, I want all counters to reach t ...

Implementing model synchronization on server initialization with Next.js and sequelize

When it comes to using Express with React on the backend, I'm accustomed to working in a server.js file to synchronize the database. However, I've recently started working with Next.js and noticed that there's no server.js file to sync the m ...

Regular expression is used to limit input to integers only, specifically numbers between -130 and 30

Completed the regex for 0 to 50 ^(?:[1-9]|[1-4][0-9]|50)$ The current regex is functioning correctly. Next step is to create a regex that includes negative numbers, allowing for values between -130 and 30 without any decimal points. ...

Avoid HTML code injection in an ExtJS4 grid by properly escaping the href attribute

I am facing an issue with escaping HTML in my Extjs grid. I have used the following configuration : return Ext.String.htmlEncode(value); In the renderer of my column, this method works perfectly for simple HTML tags like h1, b, i, etc. However, if I in ...

Differentiating between an individual array and an array containing multiple arrays

Can jQuery differentiate between a regular array, an array of arrays, and an array of objects? var a = [1,2,3]; var a2 = [[12,'Smith',1],[13,'Jones',2]]; var a3 = [{val:'12', des:'Smith', num:1}]; //a = regular arr ...

Executing javascript code that has been inserted into inner HTML is not functioning as expected

Trying to retrieve a response from another page, specifically named ajaxresponse.php, through an AJAX request. I also aim to execute some JavaScript actions on that ajaxresponse.php page, but the JavaScript code is not functioning as expected. Although I a ...

Collapse or expand nested rows within a dynamic table using Bootstrap Collapse feature

I am currently working on creating a dynamic leaderboard table for a sports league using data from a SQL database. The league consists of multiple teams, each team has different players (with some players belonging to more than one team), and players earn ...

Ways to confirm non-null values and bypass the row if it is

I have been attempting to compare 2 dates in order to appropriately display data in a table. I have tried the following approach: ${this.dateToCompare.getTime()} > ${row.CreateDate.getTime()} However, there is an issue where CreateDate has a null value ...

How can I load only specific images on a webpage using HTML?

I attempted to implement an image filter for my website by using the code below: <script> function myFunction() { // Initialize variables var input, filter, ul, li, a, i; input = document.getElementById('myInput'); filter = input.value.toU ...

Exploring end-to-end testing with NestJS and Guards

I'm trying to test an endpoint called /users using nestjs, but I encountered some errors. I'm unsure how to fix the issues and make the test pass with a guard. First Issue Nest is unable to resolve dependencies of the UserModel (?). Please en ...

What is the best way to create a JavaScript Up/Down Numeric input box using jQuery?

So, I have this Numeric input box with Up/Down buttons: HTML Markup: <div class="rotatortextbox"> <asp:TextBox ID="txtrunningtimeforfirstlot" ClientIDMode="Static" runat="server">0</asp:TextBox> (In mins) </div> <div cl ...

Two separate ajax functions executed sequentially both yield identical results

I am encountering a strange issue with 2 different ajax functions being called consecutively. Each function fetches a different value and populates different text boxes, but they both return the value of the first function called. Here is the code snippet ...

Tips for accurately extracting values from a decoded JSON

Hello, I am posting this query because I recently encountered an issue with json encoding in PHP. When using the json_encode() function, my original JSON data gets converted to strings instead of maintaining its original variable type. For instance, let&a ...

Is there anyone available to assist me with this contact validation form?

I'm struggling to make this contact form highlight red and display 'not valid' inside the boxes. Despite my efforts, I just can't seem to get it to work! I'm unable to change the existing HTML tags, but I can add to the HTML. I wan ...

Filling a martial arts training center's drop-down menu with choices using an Ajax response message

Within my application, there are two drop down menus. The first drop down menu allows users to select the type of institution, and I have added an onchange event that triggers a JavaScript function to make an AJAX call in order to populate the second drop ...

When I toggle the div to close on mobile, I want it to show on desktop

My attempt at creating a toggle button to hide and show content was not successful. I struggle with coding in Javascript/Jquery. In the desktop view, the description displays perfectly (see image here), but in mobile view, there is a button to toggle hidi ...

What is the best way to execute multiple controller functions for a single route?

I have a specific route set up for users to submit loan applications. What I want to achieve is to call different controller functions based on the amount of the loan that the user is applying for. app.use('/submitLoanRequest50kMore', mw1, mw2, ...

Utilize D3's pie chart to showcase the data in JSON's individual collections

I am currently working on creating a pie chart that displays the distribution of collections based on their names. I have come across an issue where d3.layout.pie().value() only evaluates specified array values. Is there a solution available to extract the ...

Guide to making an `Ajax Login` button

I am interested in creating a SIGN IN button using ajax. Specifically, I want it to display something (such as welcome) on the same page without refreshing it. This is the progress I have made so far: update2: <form id="myForm" onsubmit="return signi ...