How do I add a new stage within the $group operator in MongoDB?


Desired Outcome:

[
  {
    "_id": "nourishing",
    "doc_count": 2,
    "ingredients": {
      "Broccoli": {
        "5g": 1,
        "10g": 1
      },
      "Tomatoes": {
        "20g": 1,
        "25g": 1
      }
    }
  },
  {
    "_id": "unhealthy",
    "doc_count": 3,
    "ingredients": {
      "soda": {
        "200ml": 1,
        "300ml": 2
      },
      "chips": {
        "50g": 1,
        "75g": 1,
        "90g": 1
      }
    }
  }
]

Aggregation Preview: Experiment1

db.collection.aggregate([
  {
    $group: {       
      "_id": "$category",  
      "ingredients": {
        $push: "$$ROOT"  
      },
      "doc_count": {
        $sum: 1        
      }
    }
  }
])

Furthermore,

I've identified an Additional Step to transform the food items array as well: Experiment2

However, this process covers all data sets. I intend to apply the methodology in "Experiment2" solely for the ingredients category within each respective cluster entity.

This is akin to amalgamating both Experiment1 and Experiment2. How can I achieve this?

Answer №1

db.collection.aggregate([
  {
    "$set": {
      "ingredients_info": {
        "$objectToArray": "$ingredients"
      }
    }
  },
  {
    "$unwind": "$ingredients_info"
  },
  {
    "$group": {
      "_id": {
        type: "$type",
        ingredient: "$ingredients_info"
      },
      "count": {
        "$sum": 1
      },
      "doc_count": {
        "$addToSet": "$item"
      }
    }
  },
  {
    "$group": {
      "_id": {
        type: "$_id.type",
        ingredient: "$_id.ingredient.k"
      },
      "docs_count": {
        "$push": {
          k: "$_id.ingredient.v",
          v: "$count"
        }
      },
      "doc_count": {
        "$push": "$doc_count"
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.type",
      "ingredients_list": {
        "$push": {
          k: "$_id.ingredient",
          v: {
            "$arrayToObject": "$docs_count"
          }
        }
      },
      "doc_count_total": {
        "$push": {
          $reduce: {
            input: "$doc_count",
            initialValue: [],
            in: {
              $concatArrays: [
                "$$value",
                "$$this"
              ]
            }
          }
        }
      }
    }
  },
  {
    "$set": {
      "unique_ingredients": {
        "$arrayToObject": "$ingredients_list"
      },
      doc_count: {
        "$size": {
          "$setUnion": {
            $reduce: {
              input: "$doc_count_total",
              initialValue: [],
              in: {
                $concatArrays: [
                  "$$value",
                  "$$this"
                ]
              }
            }
          }
        }
      }
    }
  }
])

Explore on mongoplayground

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

Is there a way to extract the content length from the raw DraftJS data?

I have a system where I am storing the data from my DraftJS editor in my database as a JSON string by passing it through convertToRaw(editorState.getCurrentContent()). For example, this is how the stored data looks like in the database: {"blocks": [{"key ...

When trying to access Ajax fetched data within a VueJS `router-view`, the `$root` object returns undefined only when navigating directly to

As I familiarize myself with vuejs, I decided to challenge myself by creating a webpage similar to an eshop for practice purposes. My approach involves fetching all the necessary data in a single api call to ensure easy access from all my router-views for ...

Struggling to successfully pass my variable from jQuery (or javascript) to the following page

I'm currently editing a PHP script to pass variables to the next PHP page using a jQuery (or javascript) script instead of a form with the POST method. After reviewing the entire jQuery (or javascript) script and understanding how the author passes hi ...

Using jQuery to toggle the selection of multiple checkboxes

Let's start fresh, no need to worry! This is simply a jQuery question ;) I am currently working on a PHP code where the user sends a query to our database. The form then displays sets of results grouped in tables, each with checkboxes to select the d ...

Angular filtering is not functioning as expected

I have the following code in my template: <li class="row timeline-item" data-ng-repeat="item in data | filter:workoutFilter" data-ng-include="getTemplateUrl(item)"></li> And this is what I have in my controller: $scope.workoutFilter = nu ...

Dynamic fade effect with GSAP on scroll

Currently, I am attempting to implement a fade out animation with GSAP Scroll Trigger. The aim is for the page to first scroll across the X axis of the title before scrolling up and fading out. While I have made some progress, I am facing an issue where th ...

What is the best way to adjust a map to completely fill the screen?

I am experiencing an issue with my Openlayer map not fitting to full screen automatically. Despite trying various settings, I am unable to resolve this issue. Can anyone suggest what might be causing this problem? Thank you in advance https://i.stack.imgu ...

Is there a way to use MongoDB to add an object to an array and also sort it at the same time?

I am facing a challenge where I need to insert an object into an array within a MongoDB collection document and then ensure that all elements in the array are ordered based on one of their properties. To maintain uniqueness of objects in the array, I opte ...

Utilize @db.Decimal within the Prisma framework for the parameters "s", "e", and "d"

When I define the schema in Prisma like this: value Decimal? @db.Decimal(7, 4) Why do I always get this format when retrieving the value from the database: "value": { "s": 1, "e": 0, & ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Error: The request to /api/auth/login in Postman failed unexpectedly

As I am working on developing an app using node.js and express, I encountered an error while making post requests in Postman. Cannot POST /api/auth/login%0A Below are the details of my app's structure along with the files involved: app.js const ex ...

Encountering a 'TypeError: app.address is not a function' error while conducting Mocha API Testing

Facing an Issue After creating a basic CRUD API, I delved into writing tests using chai and chai-http. However, while running the tests using $ mocha, I encountered a problem. Upon executing the tests, I received the following error in the terminal: Ty ...

Looking for a way to efficiently retrieve results by matching multiple string keywords as you go through each line of a file (fs)?

Essentially, I have multiple search strings provided by the client that need to be matched with each line in a file. If a line matches all of the inputted strings, I should add that line to the results array. However, when I run the code below, it only ret ...

Issue with handlebars template

Below is a handlebars-template that I have: <script id="pins-list-template" type="text/x-handlebars-template"> {{#if ListCount > 0}} <ul> {{#each ListData}} <li> <img src="assets ...

javascript/jquery concatenate all hidden input values into a variable

I am working with a collection of tags that are each added to a hidden input labeled "item[tags][]". <input type="hidden" style="display:none;" value="first" name="item[tags][]"> <input type="hidden" style="display:none;" value="second" name="ite ...

The Intricacies of MongoDB Indexing

I am a big fan of MongoDB, using it both at work and home without encountering any performance, complexity, or limitation issues so far. However, my mind has been preoccupied with thoughts about indexes lately, leading me to a question that I haven't ...

Setting up Redux Saga in a modular format

I am currently using create-react-app for my project. As I now need redux-saga to handle async operations, I am encountering an issue with setting up sagas in a modular manner. When I say modular, I mean having one main sagas file that exports all the comp ...

Organizing items by a string attribute in TypeScript

My data consists of an array of objects with a structure similar to this: export class AccountInfo { accountUid: string; userType: string; firstName: string; middleName: string; lastName: string; } NOTE: I opted not to use an enum for userType ...

ERROR: No compatible version of jQuery Foundation could be located

Encountering issues while installing Foundation due to conflicts with Jquery. λ bower install foundation bower foundation#x cached https://github.com/zurb/bower-foundation.git#5.5.1 bower foundation#x validate 5.5.1 against https: ...

Different time parameter for setting a timeout in Javascript

I am struggling to create a slideshow with varying time intervals for each image. My knowledge of Javascript is limited, and I have been working on resolving this issue for quite some time. /* function ShowEffect(element){ new Effect.Appear(element, ...