Using the $group operator with a nested array component

Can you show me how to utilize MongoDB's aggregation feature to summarize the count of each reason_id?

I have noticed that there are 2 counts for "reason_id = KW7Kcsv7835YZeE3n" and 1 count for "reason_id = KNcKQCjhFzha3oLfE".

Below is the dataset:

[
  {
    "_id": "2DLQFJLbZScBXpSam",
    "toilet_id": "bJsyfh3TCvpTzE2mJ",
    "reason_ids": [
      "KNcKQCjhFzha3oLfE",
      "KW7Kcsv7835YZeE3n"
    ],
    "score_id": null,
    "toilet": {
      "_id": "bJsyfh3TCvpTzE2mJ",
      "name": "Toilet_M_1",
      "gender": "m",
      "mac_address": "11:11:11:11:11:11"
    }
  },

  {
    "_id": "akjsbcjascklsacas",
    "toilet_id": "bJsyfh3TCvpTzE2mJ",
    "reason_ids": [
      "KW7Kcsv7835YZeE3n"
    ],
    "score_id": null,
    "toilet": {
      "_id": "fsgndgklndsdsdsd",
      "name": "Toilet_F_1",
      "gender": "f",
      "mac_address": "11:11:11:11:11:11"
    }
  },
]

Answer №1

You may want to consider using the following code snippet:

db.collection.aggregate([
  {
    "$unwind": "$reason_ids"
  },
  {
    "$group": {
      "_id": "$reason_ids",
      "count": {
        "$sum": 1
      }
    }
  }
])

The expected output is as follows:

[
  {
    "_id": "KW7Kcsv7835YZeE3n",
    "count": 2
  },
  {
    "_id": "KNcKQCjhFzha3oLfE",
    "count": 1
  }
]

Feel free to test it out 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

Is there a way to display a specific dropdown menu depending on the checkbox that is selected?

I have a bunch of checkbox items, including one labeled nocalls, as well as a couple of dropdownlist boxes. Here are the dropdown boxes: <tr> <td align="right"><FONT class="Arial10"><B>Profile<font color="#ff0000">*</ ...

Node: effectively managing SQL scripts with dynamic variable replacement

My SQL statements have grown quite large, and I want to store them as separate files with syntax highlighting. The solution I found on StackOverflow is perfect for my needs. In my case, I write SQL queries in JavaScript using Template Literal syntax for v ...

Using the "i" parameter in a Lodash for loop results in undefined, however, it functions properly with specific values set

My goal is to use Lodash to search for specific integer values in an object and then store some of those values in an array. The integers are variable and come from a separate array, but I am consistently getting undefined as the result. If I manually inp ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

When inside a function declaration, io.socket is not defined, but it is defined outside of

Trying to utilize io.socket for a POST call to a controller action is presenting some unexpected behavior. Interestingly, when using io.socket.someMethod() within script tags as shown, it works smoothly: <script> io.socket.post('/visualization/ ...

What is the optimal location for storing component fetch logic?

When should I make a REST request to retrieve data for a Vue component called Page, specifically for the properties title and content? Also, where is the best place to handle this logic? Currently, I am trying to fetch the data on the component's rea ...

Guide on transferring value from a <select> element using JavaScript

I'm attempting to pass the selected value of a <select> in the onChange function. I've explored this question on SO, but unfortunately, using this and this.value hasn't been successful. I understand that the question is quite old... se ...

Enhance text by hovering over it

I am currently working on implementing a unique feature using jQuery and CSS. Rather than just inheriting the width, I want to create a magic line that extends to the next index item. Scenario: 1: Hover over Element one ELEMENT ONE ELEMENT TWO ELEM ...

Encountering an error with $mdDialog.alert

I am attempting to activate an Alert Dialog using Angular Material Design. Within my controller, I have: angular.module('KidHubApp') .controller('ActivityCtrl', ['$scope','$meteor', '$stateParams', &apo ...

Leverage Vue's ability to inject content from one component to another is a

I am currently customizing my admin dashboard (Core-UI) to suit my specific needs. Within this customization, I have an "aside" component where I aim to load MonitorAside.vue whenever the page switches to the Monitor section (done using vue-router). Here ...

Tips for aggregating the values of object arrays in React props

I need help sorting three top-rated posts. Currently, the function displays three post titles along with their ratings, but they are not sorted by best rating. Can anyone assist me with this issue? {posts.slice(0, 3).sort((a, b) => ...

Converting a jQuery function into AngularJS: A step-by-step guide

I'm completely new to AngularJs and I recently created a slider function using jQuery. Now, my goal is to convert this function into Angular. Below is the code snippet that I have: <div class="slide-container"> <div class="slide-s ...

Exploring MongoDB: Querying arrays of nested documents

After extensive research, I have not been able to find a precise solution to my query. The data structure in question is as follows: stname: "SC", dob : "1985", education {[ {name : Lancaster, year : 2013}, {name : Ma ...

The code snippet 'onload='setInterval("function()",1000)' is not functioning as expected

I need to continuously load the contents of an XML file into a specific HTML div every second. Here is the JavaScript code that I am using to parse the XML file: function fetchEntries() { if (window.XMLHttpRequest) req = new XMLHttpRequest(); ...

Issue: requireJS configuration is invalid

Here is the file structure of my project - src |- main.js |- math.js The math.js file acts as an AMD module and is being required in main.js. I have npm installed require.js and included it in main.js. //main.js var rjs = require('requirejs' ...

Monitoring and recording Ajax requests, and retrying them if they were unsuccessful

As a newcomer to Javascript, I'm diving into the world of userscripts with the goal of tracking all Ajax calls within a specific website. My objective is to automatically repeat any failed requests that do not return a status code of 200. The catch? T ...

Reading a JSON file using Javascript (JQuery)

Struggling to figure out how to handle a JSON file using JavaScript. Here are the details : { "streetCity": { "132":"Abergement-Clemenciat", "133":"Abergement-de-Varey", "134":"Amareins" } } I am attempting to access ...

Establishing standard emit actions in a Vue JS component layout

I am dealing with a complex situation involving two nested Vue JS components. The child component is emitting certain events to the parent function, which I have defined within the parent component declaration. The issue here is that these events are being ...

The setInterval function is malfunctioning

If I have the following function: function check(){ alert("Welcome"); } window.onload = check(); setInterval("check();", 5000); However, it is not working properly. Oddly enough, when I refresh the page, it works as intended. How can I resolve this i ...

Queries using the $elemMatch operator in MongoDB are experiencing issues with indexes

My query using $elemMatch is not utilizing the index I added for it. Can anyone help? Below is a sample document: { "_id" : "123466", "something" : [ { "someID" : ObjectId("5701b4c3c6b126083332e66f"), "tags": [ ...