Grouping nested arrays in a single document with MongoDB

My Collection is structured as follows:

{
    id: 23423-dsfsdf-32423,
    name: Proj1,
    services: [
         {
            id:sdfs-24423-sdf,
            name:P1_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-24jhh-sdf,
            name:P1_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-2jnbn3-sdf,
            name:P1_Service3,
            products:[{},{},{}]
         }
    ]
},
{
    id: 23423-cxcvx-32423,
    name: Proj2,
    services: [
         {
            id:sdfs-xvxcv-sdf,
            name:P2_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-xvwqw-sdf,
            name:P2_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-erdfd-sdf,
            name:P2_Service3,
            products:[{},{},{}]
         }
    ]
}

I am looking to retrieve a document containing an array of all services:

{
    services: [
         {
            id:sdfs-24423-sdf,
            name:P1_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-24jhh-sdf,
            name:P1_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-2jnbn3-sdf,
            name:P1_Service3,
            products:[{},{},{}]
         },
         {
            id:sdfs-xvxcv-sdf,
            name:P2_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-xvwqw-sdf,
            name:P2_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-erdfd-sdf,
            name:P2_Service3,
            products:[{},{},{}]
         }
     ]
}

The query I tried was:

db.projects.aggregate({"$group":{"_id":"services","services":{"$push":"$services"}}})

However, this resulted in nested arrays within the document. I need a flat array of objects:

{
    _id:"services",
    services:[
        [
            {
            id:sdfs-24423-sdf,
            name:P1_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-24jhh-sdf,
            name:P1_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-2jnbn3-sdf,
            name:P1_Service3,
            products:[{},{},{}]
         }
        ],
        [
            {
            id:sdfs-xvxcv-sdf,
            name:P2_Service1,
            products:[{},{},{}]
         },
         {
            id:sdfs-xvwqw-sdf,
            name:P2_Service2,
            products:[{},{},{}]
         },
         {
            id:sdfs-erdfd-sdf,
            name:P2_Service3,
            products:[{},{},{}]
         }
        ]
    ]
}

I am struggling with how to properly aggregate or join the arrays together. This step is crucial before moving on to consolidating all products as well.

Thank you!

Answer №1

In order to consolidate all services into a single document, it is necessary to group by null _id. It's also important to use the $unwind operator on the services array before grouping to prevent ending up with an array of arrays.

db.project.aggregate(
  {$unwind: '$services'},
  {$group: {_id:null, services: {$push: '$services'}}}
)

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

How can you utilize Node.Js and Promises to successfully fulfill a promise and return it?

In my current Mongoose setup, I am facing a scenario where I need to search for a customer in the database. If the customer exists, I should return their customerId. However, if the customer does not exist, I want to create them and then return the custome ...

Inquiring about how to make the pieces move on the checker boards I created

I'm having trouble getting my SVG pieces to move on the checkerboard. Can someone please help me figure out how to make them move, even if it's not a valid move? I just want to see them in motion! The important thing is that the pieces stay withi ...

Using jquery-url in a nodejs environment

I am currently attempting to migrate a piece of JavaScript code that relies on jquery-url from jQuery to Node.js. The specific function in question uses jquery-url to extract the hostname from a given URL, like so: var host = $.url(url).attr('host&a ...

Unable to add npm package at this time

Feeling a bit desperate right now. I recently implemented npm and grunt to enhance my development process, which was working smoothly until today. Suddenly, I'm unable to install npm packages and keep encountering the following error message: 0 info ...

Having difficulty installing the npm package canvas

I've been struggling to get the npm package called canvas installed all day. I tried running this command: sudo npm install canvas However, I encountered the following error: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

When using async functions in iterative processes

In my current setup, I am utilizing a for-each loop to handle a list and specifically require element n to be processed only after element n-1 has completed: let elements = ["item1", "item2", "item3"]; elements.forEach(function(element){ someAsyncFun ...

Having trouble accessing req.user on my Node.js server using Auth0 and Angular

Currently, I am utilizing auth0 for my admin panel's login system and it is functioning smoothly. However, I have encountered an issue in node where 'req.user' is returning as undefined for some unknown reason. This setup is fairly basic; I ...

The installation process in npm is consistently sluggish

Every time I run npm install --no-optional, it takes about 3 minutes to complete and installs around 200MB of files. I've been trying to find ways to speed up the build process, but haven't had much luck. Shouldn't npm install cache depende ...

Troubleshooting a node-gyp issue with Karma

Hi there! I'm facing an issue while trying to set up karma using npm. After fetching the packages, the terminal seems to hang on the final build error message. To install karma, run this command: npm install -g karma During installation, some conso ...

Fixing problems encountered when asynchronously gunzipping an already read file in Node.js

As a newcomer to the world of node.js and asynchronous programming, I have successfully used promises to read files with fs readFile, but I am struggling with getting zlib Gunzip to function as expected in my Coffeescript code: promisifyRun(fs, 'r ...

Using indented, multi-line logging in a NodeJS environment can help to

I'm looking for a way to display objects that have been printed with JSON.stringify() in the console, specifically within the context of a Mocha test suite output. While my tests are running, I want the object log lines to be indented further to the ...

Troubleshooting: "Application Error" when running Node app on Heroku

2020-01-28T01:42:46.028688+00:00 heroku[web.1]: Initiating process with command npm start 2020-01-28T01:42:45.000000+00:00 app[api]: Compilation completed successfully 2020-01-28T01:42:48.451589+00:00 heroku[web.1]: Transitioned from starting to cras ...

When attempting to insert the "$binary" key into MongoDB using Node.js, an error occurs stating that the key must not begin with a "$" symbol

When utilizing the node driver to insert records into mongo, I encountered an issue with a certain field in my collection: { "$binary": "base64 encoded binary" }. If I directly input a key beginning with $, it triggers an error: Error: key $binary must no ...

Having difficulty updating my npm package manager for node

When attempting to update my node package manager using the command npm install -g npm on my Windows system, I encountered an error that prevented me from updating successfully. PS C:\Users\LENOVO\Desktop\Toggle-Theme> npm install -g ...

The system cannot locate the "default" task. Please consider using the --force option to proceed. The process has been halted due to warnings

Below is the content of my gruntfile.js file var fs = require("fs"), browserify = require("browserify"), pkg = require("./package.json"); module.exports = function(grunt) { grunt.initConfig({ mochaTest: { test: { options: { ...

The problem with utilizing the Node `util.inherits` method

I have encountered an issue with a 'this problem' in a Node server. It seems that replacing worker.stuff with worker.stuff.bind(worker) is necessary for it to function correctly. Is there a way to incorporate the bind method into the Worker Clas ...

My issue with express routing not functioning properly across various discord servers

While working on a Discord bot that accesses routes from Express, I encountered an issue. It seems to function properly when kept on a specific server, but if I try accessing Express on a different server while it's running, I encounter the error "ass ...

"You have entered an invalid configuration object" error message appears after generating a package.json file using the "npm init" command

Previously, I had a functioning webpack configuration. However, after utilizing npm init to generate the following package.json file: { "name": "y", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \" ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

I'm having trouble retrieving data from the server using the AngularJS $http.get() function. What am I doing wrong

Ensure that your question is clear and that your code properly showcases the issue at hand. Feel free to leave any questions or comments below for clarification. app.js var express = require('express'); var app = express(); app.use(express.sta ...