What is the best way to perform nested array aggregation queries in MongoDB while also projecting specific fields

Looking to extract suppliers and customers from the given data using mongodb aggregate function, projecting specific fields while removing the rest.

 {
        "_id" : ObjectId("577f9a25bea25d480d8f1895"),
        "password" : "12345",
        "mobile" : "9582223889",
        "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="741534165a171b19">[email protected]</a>",
        "name" : "ashiush jindal",
        "invoice" : [{
            "name" : "Ashish Jindal",
            "dname" : "jindalbe",
            "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f2e0f2d612c2022">[email protected]</a>",
            "password" : "12345",
            "role" : ["customer"]
          }],
        "inventory" : [{ }, {
            "item" : "Levis Jeans",
            "sku" : "12345",
            "buy" : [{
                "bp" : "jindalbe",
                "qty" : 50,
                "created" : "9/7/2016"
              }]
          }, {
            "item" : "Levis Trouser",
            "sku" : "123",
            "selling_price" : 2000,
            "buy" : [{
                "bp" : "jindalbe",
                "qty" : 90,
                "created" : "9/7/2016",
                "price_per_qty" : 1000
              }, {
                "bp" : "jindalbe",
                "qty" : 60,
                "created" : "9/7/2016",
                "price_per_qty" : 1000
              }, {
                "bp" : "jindalbe",
                "qty" : 60,...

Extracting supplier names from business partners list as shown below:

{
   suppliers:["Ashish Kumar"]
}

Using aggregation query for this purpose:

The attempted solution is as follows:

          [
                { $match: { "_id": ObjectId(req.headers["token"]) } },{
                    $project: {
                        suppliers: {
                            $filter: {
                                input: '$business_partner.role',
...

Answer №1

To extract unique suppliers associated with a specific business partner in MongoDB, you can unwind the arrays and apply match conditions followed by grouping them together using $addToSet:

db.device.aggregate([{
  "$unwind": "$business_partner"
}, {
  "$unwind": "$business_partner.role"
}, {
  "$match": {
    "_id": ObjectId("577f9a25bea25d480d8f1895"),
    "business_partner.role": "supplier"
  }
}, {
  "$project": {
    "_id": 1,
    "business_partner": 1
  }
},{
    "$group": {
        _id:"$_id",
        supplier: {
            $addToSet: '$business_partner'
        }
    }
}]);

This approach is compatible with mongo 2.6 (without using $filter).

The resulting output will look like this:

{
  "_id": ObjectId("577f9a25bea25d480d8f1895"),
  "supplier": [{
    "name": "Ashish Kumar",
    "dname": "jindal",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6908290b470a0604">[email protected]</a>",
    "password": "12345",
    "role": "supplier"
  }]
}

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

JSON endpoint in Express route experiencing timeouts

I am relatively inexperienced with Node, React, and Express, although I have previously deployed a React application with a Node server successfully. This time, however, I am deploying on AWS for the first time and encountering some differences compared to ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

Difference between Angular2 import syntax: "use 'import * as <foo>'" or "use 'import {<foo>}'"

There are two different ways to import modules that I have noticed. Most imports seem to follow this syntax: 'import {<something>} (for example, import { Component } from '@angular/core';) The other way of importing looks like this: ...

When the email field is changed, the string is not being set to the state if it is

I encountered a strange issue while setting an email input as a string to state. Even though I can see on React Dev Tools that it gets sent, when I try to log it from another function, I get an empty string. The odd part is, if I change the order of the in ...

What potential side-effects could occur from cloning the entire state object in React?

Upon reviewing a React code base I'm currently working on, I've noticed a recurring pattern that concerns me regarding potential bugs. Here is an example of the code in question: const newState = Object.assign({}, {}, this.state); newState.x = ...

Troubleshoot: Issue with Navbar Dropdown Expansion on Bootstrap Sass 3.3.6 with JavaScript

Beginner: Bootstrap Sass 3.3.6 - Incorporating Javascript - Issue with Navbar Dropdown Not Expanding application.html.erb Head: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> ...

What is the best way to utilize node packages?

Apologies for the novice question. I am just starting out with coding and have spent several hours searching online for instructions on how to run code from node modules, but unfortunately, haven't made much progress. My goal is to create an editable ...

Guide to resizing and shifting to the right using CSS techniques

As a backend developer with experience in nodejs, I am diving into the world of web application development. HTML5 and CSS are new territories for me, but you can check out my small web application here. Now, I am looking to incorporate animations into my ...

Retrieve information from ngResource and then connect the output to the display

I am currently working on a project using AngularJS. At the moment, I am using ngResource to retrieve JSON data from a static file, with plans to potentially switch to a database in the future. In my approach, I have set up a controller to call the servic ...

The current status of the ajax call is set to 0

I am currently attempting to retrieve information from a remote server on my local machine. The readyState seems to be fine, equal to 4. However, the status is consistently showing as 0 instead of 200. When I click the button, it doesn't return anythi ...

"Commander.js does not process query strings when used in conjunction with node

I developed a CLI tool using commander.js which has been released on npm. This command-line interface utilizes node-fetch to fetch data from an external API. However, I have received reports from some users stating that the query string in the fetch URL is ...

Troubleshooting NodeJS CORS issue in Vue project as localhost API calls fail

Having an ongoing project that utilizes a NodeJS/Express backend and a VueJS frontend, I am consistently encountering CORS errors: Cross-Origin Request Blocked: The Same Origin Policy restricts access to the external resource at https://localhost:8080/api ...

Validating RSS Feeds with Javascript

Hey, I'm looking to replicate something like this: I want to verify RSS feeds before submitting a form. <form name="form1" id="form1"> <input type="text" name="url" type="text" id="url" /> <input type="submit" name="submit" id="bu ...

Tips for structuring a news thread with a staggered approach

On my Drupal 8 website, I have set up a newsfeed. How can I display the news items in staggered rows? I would like the first item to align on the left and the second item to be on the right, repeating this pattern for all subsequent items. Currently, I am ...

Unable to display Polygon using ReactNativeMaps

Having trouble displaying the polygon correctly on my screen. I suspect it's due to receiving an array of objects from my API. This is the code snippet in question: <MapView.Polygon coordinates={poligonofinale} strokeColor="#000" fillColor= ...

How can I combine multiple textures from mtlLoader and objLoader in three.js?

I have the files .mtl, .obj, and several .jpg textures. I have been attempting to use different textures in the export loader OBJ, and while I can see my object on the scene, it appears as a black color. Can anyone spot what might be incorrect or missing ...

Is resizing possible using the Canvas identifier?

Is it possible to adjust the canvas size to match the width of the page using the canvas id's style in the html? Then in your javascript code for the canvas, can you have resize listeners that are responsive to the canvas size at any given time? I c ...

Step-by-step guide on generating an index through mongoose and elastic search in a node.js and express.js environment

I am looking to set up the index in elastic search using mongoose and express, but I have not been able to find any documentation on how to do it. I attempted to use mongoosastic, but it did not meet my needs. Is there anyone who can assist me with this? ...

Tips for uploading files in filepicker with protractor

https://i.sstatic.net/noq46.png Here's a snippet of HTML code you might find useful: <input type="file" class="fileUploadInput" name="fileUpload" id="fileUploadInput" accept="application/msword,application/pdf,text/plain,application/rtf,applicat ...

JavaScript prohibiting input prior to execution

Having trouble with executing this javascript before the user input, can anyone assist me in resolving this issue. I just want to create a simple html page with a textbox and a button. When the button is clicked, it should open a new window with a modifie ...