The process of determining array.reduce between two collections in MongoDb

I have two MongoDB collections with a one-to-one relationship. I want to perform an array.reduce operation based on both of these collections, like so:

CollectionA: [
  { _id: 1, valueA: 234, idB: 1 },
  { _id: 2, valueA: 64, idB: 2 },
  { _id: 3, valueA: 456, idB: 3 },
]

CollectionB: [
  { _id: 1, valueB: 678 },
  { _id: 2, valueB: 11 },
  { _id: 3, valueB: 4005 },
]

I want to calculate the sum of:

sum(valueA - valueB)

Is it possible to achieve this with a single database request? If not, what is the most elegant approach?

Answer №1

To achieve the desired results, you can utilize the aggregation-pipeline in MongoDB.

Here is a sample query structure for your reference:

db.CollectionA.aggregate([
    {
        $lookup: {
            from: 'B',
            localField: 'idB',
            foreignField: '_id',
            as: 'objB'
        }
    },
    { $unwind: '$objB' },
    {
        $project: {
            subField: {
                $subtract: ['$valueA', '$objB.valueB']
            }
        }
    },
    {
        $group: {
            _id: null,
            sum: {
                $sum: '$subField'
            }
        }
    },
    {
        $project: {
             totalSum: 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

Leveraging JavaScript to trigger onClick() functions for multiple buttons throughout a webpage

        While searching for solutions, I came across several articles with similar topics, but unfortunately, none of the proposed solutions worked. Please forgive me if it was due to my own error. Background I am assisting a client who is transition ...

Executing code upon the completion of jquery's slideUp() function

Is there a method to trigger the execution of html() only after the completion of slideUp()? <p class="test">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent tortor elit</p> $(".test").slideUp().html(""); I attempted using ...

Implementing Google Calendar access token in JavaScript: A practical guide

I have a question about Google Calendar and I'm hoping you can assist me. I currently have an access_token from Google Calendar that has been stored in the localStorage. const googleAccessToken = e.vc.access_token; localStorage.s ...

Steps to align div directly to the left of the button that was clicked

I have a div in my code that is hidden by default. I want to show this div exactly left whenever the user clicks on the show button. Since there are multiple show buttons on my page, I would like to display the div as described above. <div id="me ...

What is causing the ajax code to malfunction?

I am new to ASP MVC and trying to create a login form using AJAX. I have written a JsonResult in the controller to check the username and password, but for some reason it is not working. Here is my controller code: public ActionResult login() { ...

js Display Type Error

Here is a snippet of JavaScript code that seems to be causing an issue: needSubIdCheck = $("#needSubIdCheck").text(); liveSupplierCount = $("#liveSupplierCount").text(); subIdCount = $("#subIdCount").text(); if(needSubIdC ...

Sending requests across domains from HTTPS to HTTP with callback functionality, and reversing the process

Prior to our conversation, I had created it using Flash. I uploaded a special file (crossdomain.xml) on the server side (https), while the Flash component was placed on the http server. Although they belong to different domains on the https and http serv ...

The date entered in the input field should also appear in all other textboxes on the

I currently have 2 tables set up on my page. In the first table, there is a textbox (txt1) that includes a date picker. The second table contains 5 similar textboxes (txt2, txt3, txt4, txt5, txt6) also with date pickers. My requirement is as follows: Ini ...

When working with props.data in MDBNav, learn how to set the active TAB or LINK

Utilizing ReactJS, I am incorporating MDBNav from MDBreact. https://i.sstatic.net/IQtEe.png This snippet demonstrates the container where props.data is defined: import React from 'react' import MiTabs from "../componentes/MiTabs"; class VpnLi ...

The appearance of the upload button in React using Material-UI seems off

After following the MUI document on React Button upload, I noticed that the UI results were different than expected. Instead of just showing the button UI, there was an additional UI element present. By adding the sx={{display:'none'}} property, ...

Experiencing difficulties launching my Server.JS due to a listening error

Hey there, I'm struggling to get my server.js up and running. Whenever I try to run node on it, I keep getting the error message "listening on *:3000". Below is the code for my server.js: var app = require('express')(); var http = require(&a ...

Creating interconnected circles with lines utilizing canvas

I am currently utilizing the canvas tag to generate circles on a world map image. My objective is to link these multiple circles with lines using the Canvas tag. Although I have successfully drawn the circles, I am facing difficulty in drawing the connecti ...

The AJAX request function in JavaScript seems to be failing to return any response

I am currently working on a registration page where users can check the availability of their selected username without having to reload the entire page. The PHP script 'usernameAJAX.php' is responsible for querying the database and returning a r ...

URL for image preview on Amazon S3

Is there a way to retrieve preview images from my Amazon S3 image storage instead of always fetching the full-sized 5MB images? If necessary, I would then be able to request the normal image. ...

What is the purpose of these specific Javascript expressions (+!)?

Currently, I am attempting to convert JavaScript code into Python. One of the challenges I am facing is understanding the purpose of certain expressions, which has left me feeling stuck. Below is the segment of code that I am trying to translate. va ...

What is the best way to eliminate opacity in an element using react dnd?

When I use react-dnd to drag an item, the element being dragged becomes almost completely opaque. I would like to increase its visibility, is there a way to achieve this? In the image below, the upper element is the one being dragged and the bottom one is ...

The functionality of window.event.target appears to be malfunctioning in the Firefox browser

I have been working on an angularjs application. We have implemented a functionality to display alerts for unsaved changes using window.event.target. Everything was functioning correctly in all browsers except for <code>Firefox. The error message w ...

I am encountering difficulties trying to create a draggable stacked bar chart using d3 v4. The main challenge lies in properly translating the svg elements during the dragging process

const dragFunction = d3.drag() .on("start", startDrag) .on("drag", duringDrag) .on("end", endDrag) function startDrag(d) { d3.event.sourceEvent.stopPropagation(); d3.event.sourceEvent.pre ...

Unexpected outcome when returning a map

Encountered a puzzling issue that requires immediate clarification. When I input the following code into my project: this.metadata = json.metadata.map((x) => {return new Metadatum(x);}); console.log(this.metadata[0].value); The output consistently sho ...

The mongoose-unique-validator plugin identifies when inputs are already in use

I've been encountering an issue while trying to ensure uniqueness of email values in MongoDB. I attempted to use mongoose-unique-validator for this purpose, but it threw an error stating that the unique emails I entered already exist. Here's the ...