performing a mongoose aggregate operation on a deeply nested array

Within my schema, there is a sub array where each element references another schema in the following manner:

{
 _id: "5fed222d806311ec81d6df23"
 someOtherNestedDoc: {
    _id: "abc",
    someOtherField: 10
 },
 matches: [
   {
      _id: "5fed222d806311ec81d6daf3",
      user: "5fed222d806311ec81d6dcf3",
      probability: 10
   },
   {
      _id: "5fed222d806311ec81d6d1f3",
      user: "5fed222d806311ec81d62cf3",
      probability: 20
   },
 ]
}

I am seeking to perform a Mongoose aggregate operation that looks up the user reference for each match and projects only 3 fields - 2 existing ones and a third one which sums an array within that schema. This would result in a structure like this:

{
 _id: "5fed222d806311ec81d6df23"
 someOtherNestedDoc: {
    _id: "abc",
    someOtherField: 10
 },
 matches: [
   {
      _id: "5fed222d806311ec81d6daf3",
      user: {
         firstName: "Max",
         lastName: "Mustermann",
         totalExpenses: 100
      },
      probability: 10
   },
   {
      _id: "5fed222d806311ec81d6d1f3",
      user: {
         firstName: "Herbert",
         lastName: "Mustermann",
         totalExpenses: 200
      },,
      probability: 20
   },
 ]
}

The user entities would be structured as follows:

{
  _id: "5fed222d806311ec81d6dcf3",
  firstName: "Max",
  lastName: "Mustermann",
  password: "test",
  expenses: [
    {
      _id: 1,
     price: 50
    },
    {
      _id: 2,
     price: 50
    },
   ]
}

{
  _id: "5fed222d806311ec81d62cf3",
  firstName: "Herbert",
  lastName: "Mustermann",
  password: "test2",
  expenses: [ 
    {
      _id: 3,
     price: 75
    },
    {
      _id: 4,
     price: 125
    },
   ]
}

Answer №1

  • $unwind to break down the matches array
  • $lookup with user collection and provide user id in a variable,
    • $match based on userId
    • $project to display necessary fields and calculate total of expenses.price
  • $unwind to deconstruct the user array
  • $group by _id and rebuild the matches array
db.col1.aggregate([
  { $unwind: "$matches" },
  {
    "$lookup": {
      "from": "user",
      let: { userId: "$matches.user" },
      pipeline: [
        { $match: { $expr: { $eq: ["$_id", "$$userId"] } } },
        {
          $project: {
            _id: 0,
            firstName: 1,
            lastName: 1,
            totalExpenses: { $sum: "$expenses.price" }
          }
        }
      ],
      "as": "matches.user"
    }
  },
  { $unwind: "$matches.user" },
  {
    $group: {
      _id: "$_id",
      matches: { $push: "$matches" }
    }
  }
])

Explore the Playground here

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

What is the best way to shrink or enlarge individual sections of the accordion?

Exploring AngularJs Accordions I'm struggling to understand how to control accordions in AngularJS. I have a step-by-step module set up as an accordion and I want to collapse one part while expanding another based on completion. Here is the accordion ...

Angular does not seem to support drop and drag events in fullCalendar

I am looking to enhance my fullCalendar by adding a drag and drop feature for the events. This feature will allow users to easily move events within the calendar to different days and times. Below is the HTML code I currently have: <p-fullCalendar deep ...

How can webpages be updated in an asynchronous manner?

Consider the scenario of a website like "gmail.com," where new emails are shown in the user's inbox as soon as they arrive. From what I understand, the trigger for this comes from the database or web server updating the user's inbox page. Is the ...

Node.js throwing Res.Render is not a function error - Troubleshooting tips

I am encountering an issue where I receive an "res.render is not a function error" in the Windows 10 Command Prompt when attempting to execute my node.js code. What could be causing this error and how can I go about resolving it? Below is the content of ...

What could be the reason for v-model not functioning properly?

Embarking on my Vue.js coding journey, I am currently following a straightforward online tutorial. Utilizing the vue-cli, I kickstarted my application and crafted a basic component named Test.vue. Within this component lies a simplistic input control conne ...

Transmit responses from PHP script

I am in the process of creating a signup form where, upon clicking the submit button, all form data is sent to a PHP file for validation. My goal is to display an error message next to each input field if there are multiple errors. How can I achieve this ...

Vue: The function "priceFilter" is not defined in this context

function sanitizeInput(event) { event.target.value = event.target.value.replace(/[^\d.]/g, ""); event.target.value = event.target.value.replace(/^\./g, ""); event.target.value = event.target.value.replace(/\.{2,}/g, "."); event.targe ...

Invoke the ngrx component store's Effect in a synchronous manner

In the ComponentStore of ngrx, we have two effects. readonly startAndUpdateProgress = this.effect<void>( (trigger$) => trigger$.pipe( exhaustMap(() => this.numbersObservable.pipe( tapResponse({ next: (p ...

Styling with CSS to create a visual countdown display

I'm trying to replicate the format shown in the image below. https://i.sstatic.net/lnW2C.png Currently, this is the code I have: https://codepen.io/Brite1/pen/wvPrggj (it seems like I just need to adjust spacing and center all numbers/text). I'm ...

What is the best way to display data in the view using Angular 5 by utilizing models, classes, or interfaces?

I am facing an issue while trying to display the data fetched from my backend. I have created a class to handle the data: When I request the User by ID URI, the returned data looks like this: https://i.sstatic.net/76BSY.jpg Similarly, when I request all ...

Exploring Ngrx: Leveraging a single selector to choose multiple property modifications

I need some help with my reactive Form Angular application that uses the NGRX store. Instead of subscribing to the entire state, I want to subscribe to changes in specific fields like "name" and "city." I have been attempting to use the selector selectFor ...

Elevate a div above the rest when it is selected or dragged

I am facing an issue with draggable divs inside a parent container. Each div has a popup edit panel to modify its content. The problem arises when the divs overlap, causing the edit panel to get hidden behind another div. I want to ensure that whenever a d ...

Implementing dynamic components in Vuejs by passing props from objects

I have developed a dashboard application that allows users to customize their dashboard by adding widgets in any order. While the functionality is working fine, I am looking to address some technical debt and clean up the code. Let's simplify things ...

How to use JQuery to automatically scroll to the bottom of a

I've encountered an issue with my chat conversation update function. It runs every 2 seconds, but whenever I scroll up to read older messages, the page automatically scrolls down again when it updates. This is preventing me from reading old messages p ...

Displaying a div in Vue.js when a button is clicked and an array is filled with

Hey there! I'm having an issue with displaying weather information for a specific location. I want to show the weather details in a div only when a button is clicked. Despite successfully fetching data from the API, I'm struggling to hide the wea ...

Issue with Context Menu Not Triggering on Dynamically Added Elements in JQuery

Check out the JSFiddle Demo Within my email sidebar, I implemented a custom right-click feature that allows users to add new sub-folders. The code snippet below demonstrates how this functionality works: if ($(this).hasClass('NewSubFolder')) { ...

Encountering an issue when trying to pass a variable using a constructor

Whenever I run my TypeScript file in Angular, I encounter an error in the console. Error: compiler.js:215 Uncaught Error: Can't resolve all parameters for SearchNameComponent: ([object Object], ?). Below is my complete code: import { Component, O ...

How come I am unable to access a local JSON file using AngularJS $http?

I've been attempting to load a local file (todo.json) located in the same directory as my webpage using the following line of code: $http.get("todo.json").success( function( data ){ //Do Some logic}); However, when I try to do so, I encounter the fo ...

Tips for creating a JSON cross-domain call in PHP

Hello, I'm just starting to dive into JSON cross domain. I've encountered an issue that I need help with. I am trying to make a cross-domain call to PHP using JSON, but I keep encountering errors. Here is a snippet of the code that I'm worki ...

What is the reason behind the Nexus 4 (with Chrome for Android) displaying a window size of 384x519 while the screenshot depicts it as 768x1038

Currently, I am utilizing media queries to adjust the display based on different screen sizes. However, I have encountered an issue where the screen size is not being accurately reflected in CSS. For instance, on the Nexus 4 device, the display is renderin ...