Sum the MongoDB aggregation until a certain condition is met (using if/else) or solve the problem by counting the price and quantity

THE ISSUE

I am currently developing a function that calculates the average price and total value based on the requested quantity. For instance:

async calculateValues (first_100) {
        let market_data = await auctions_db.aggregate([
            {
                $match: {
                    item: 9999,
                }
            },
            {
                $sort: {
                    price: 1
                }
            },
            //OUTCOME
        ]);
}

//OUTCOME

At this stage, I have the following documents:

{
    item_id: 9999,
    price: 1..Number
    quantity: 1..200
    value: price x quantity //not a virtual field
},{
    another document...
}

My objective is to sum the prices until the quantity reaches or exceeds 100. In other words:

I do not want to sum the first 100 documents sorted by price ascending (in which case I would use .limit)

Currently, I am using collection.find({condition}).cursor() with the same condition and iterating through each document in a separate for loop. However, I have heard MongoDB can achieve the same result using an aggregate stage with a $cond block.

I believe that after the //Result stage, the next $operator should be a $group stage, like this:

            {
                $group: {
                    _id: "$lastModified",
                    quantity: {$sum: {$cond: if/else }" $quantity"},
                    if (below 100) {$sum: "$value" }
                }
            }

Yet, I am unsure how to implement this. Can someone provide me with an example? Or is there no substantial difference between using an aggregate stage and .find({}).cursor along with manual iteration?

Answer №1

After tackling the issue head on, I managed to come up with a solution using the syntax find({query}).cursor() and adding elements to array(s) as demonstrated below:

        let quantity_in_market = await auctions_db.find({query}).cursor();
        for (let order = await quantity_in_market.next(); order != null; order = await quantity_in_market.next()) {
            if (quantity < input_quantity) {
                quantity += order.quantity;
                price_array.push(order.price);
                value += order.buyout;
            } else {
                break;
            }
        }

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

Calculate the difference between the current value and the previous value

As I work on developing an app using vue.js, I am currently facing a minor issue. async fetchCovidDataByDay(){ const res = await fetch(`https://api.covid19api.com/live/country/${this.name}/status/confirmed`); const data = await res.json(); this ...

What is the best way to send multiple requests for the same file and retrieve the necessary response in PHP using jQuery AJAX?

var postID = $post->ID; $.ajax({ type: "POST", url: "<?php echo get_template_directory_uri();?>/b.php", data:{postID:postID}, dataType: 'json', success: function(re ...

Transferring Java producer data to Mongodb through a seamless sinking process

Using Java, I generate data and send it to a Kafka topic. Next, I want this data to be stored in MongoDB. However, when I try to send the data as JSON via Java, it fails to store in MongoDB due to the following error: [2020-08-15 18:42:19,164] ERROR Worker ...

Navigating through File URLs to access desired folders or directories

I have a group of users connected to an internal network, each with a mapped drive to a server (E:). All users are running Windows 7 and use Firefox as their browser. To allow access to MySQL files using PHP, I have set up XAMPP on the server. Currently, ...

What is the correct way to disable Mongo (in a Replica Set) without causing the database to go offline?

My server setup is as follows: I have 2 servers with a replica set for MongoDB on each. Each server functions as a single node within the replica set. My Node.js server connects to this MongoDB setup. The issue I encountered was when I shut down the sec ...

Blank YouTube Popup Modal

I am in the process of creating a pop-up modal that contains an embedded YouTube video, but my modal is not displaying properly. I am utilizing Bootstrap and have two separate sections along with JavaScript code. When the modal appears, it remains empty. I ...

Retrieve a specified number of documents for each MongoDB query match

In my collection of resources, there is a cluster field that is not unique (Number). The data is structured like this: { { _id: "0" cluster: 15 }, { _id: "1" cluster: 4 }, { _id: "2" cluster: 15 }, { _id ...

Is it possible to launch a React application with a specific Redux state preloaded?

Is there a way to skip navigating through a bulky frontend application in order to reach the specific component I want to modify? I'm curious if it's feasible to save the redux store and refresh my application after every code alteration using t ...

extraction of information from an object within an array

I am working with an array of objects containing certain keys and values. My goal is to organize these objects by key and then display all the values associated with each key together. [ { '18': 'x' }, { '17': 'y' ...

Sorting a targeted section of an already organized 2D Array based on updated values, solely if the initial sorted values align in Javascript

A challenging scenario I need help with involves an array containing objects, each with a score and a rank as shown below: [ { "score": 20, "rank": 12 }, { "score": 20, "rank": 7 }, { "score": 34, "rank": 4 } ] To begin w ...

Setting limits on relational data in Nest.js involves utilizing the appropriate decorators and methods to restrict

In my Nest.js application, I am working with relational data and using the TypeOrm query builder to retrieve the data. Here is an example of how I am querying the data: async find() { return this.landingSectionNameRepository.createQueryBuilder(&apo ...

Customize the behavior of jQuery cycle with an <a> tag

Can the jQuery cycle be accessed through a link in order to override the i variable? I've come across examples that can achieve this, but not in a scenario like this where the cycle() function is located within a variable: $(document).ready(function ...

What is the best way to integrate react-final-form with material-ui-chip-input in a seamless manner

Currently, I am utilizing Material UI Chip Input wrapped with Field from react-final-form. https://i.sstatic.net/vJKM1.jpg The main objective is to restrict the number of "CHIPS" to a maximum of 5. Chips serve as concise elements representing inputs, at ...

How to render specific components in Next.js instead of rendering the entire page using React

Currently, I am exploring how to utilize next.js to display a component within a layout upon clicking a link. The layout structure I have is as follows: import * as React from "react" import { Box } from "@chakra-ui/layout" import { L ...

Unable to modify zoom settings in iOS using javascript

My website is 1000x820 in size, but please don't ask me about responsive web design. Here's the viewport setup: <meta name="viewport" content="target-densitydpi=device-dpi, width=1000px, user-scalable=no"> When accessed on an iPhone SE w ...

What varieties of ajax styles are there?

Although I am still relatively new to utilizing ajax, I have found a lot of success in my endeavors so far. The majority of my ajax calls tend to follow this format: function saveQueryProf(){ var currentDate = new Date(); var date=currentDate. ...

When attempting to utilize putImageData on the HTML5 canvas context, an error occurs stating that the overload resolution has failed

While following the MDN canvas tutorial, I encountered an issue with a code snippet I wrote. The code is supposed to color the top left corner (50x50 pixels) of the canvas in red. However, I'm receiving an error message that says Overload resolution ...

What is the best way to pass a prop into the <router-link>?

If I replace this {{ name }}, the result is "campaigns" Now, I want to use that in my link <router-link :to="'/' + '123' + '/' + item.id"> {{ item.name }}</router-link> I attempted to substitute '1 ...

Preserving the value of a function argument for future reference

I have a function called myFunction() that accepts one argument. My goal is to save this argument to a variable and be able to access it later. Here is what I am attempting to do: When a user performs an action, an event is passed as an argument to the m ...

What is the process of specifying that an Angular directive must act as a child directive within a particular directive in Angular?

I am currently developing a directive for AngularJS. How can I specifically configure it to require being a child of directiveA? For instance, consider the following example: <my-modal> <m-header>Header</m-header> </my-modal> ...