How to efficiently search MongoDB for existing records and group them by unique array values

My dataset is structured like this:

{
    "_id" : 1,
    "category" : [
         {
           "name": "category1"
         },
         {
           "name": "category2"
         }
    ],
    "event": [
               {
                 type: "house"
               },
               {
                 type: "mouse"
               }
             ]
},

{
    "_id" : 2,
    "category" : [
         {
           "name": "category2"
         },
         {
           "name": "category3"
         }
    ]
},

{
    "_id" : 3,
    "category" : [
         {
           "name": "category3"
         },
         {
           "name": "category1"
         }
    ],
        "event": [
           {
             type: "mouse"
           }
         ]
}

I am seeking assistance on grouping the distinct category names and counting events to produce a summary document like:

{ "category1": total_count: 2,
  "category2": total_count: 0,
  "category3": total_count: 1}

Your help in solving this would be greatly appreciated.

Answer №1

This solution has been successful for me:

db.getCollection('coll').aggregate([
{$unwind: "$genre"},
{$group :{
    _id : "$genre.type",   
    total_movies : {$sum : 1}
 }
}]) 

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

Dealing with Null or Missing Fields in Loopbackjs and MongoDB

I've recently made the shift from Mysql to MongoDB as I utilize Loopback JS for my backend REST API. Throughout this transition, I've encountered an issue with query filters that previously worked seamlessly with Mysql. Here's an example of ...

Angular JS - Selecting Directives on the Fly

I'm currently developing an application where users can choose from various widgets using a graphical user interface (GUI). My plan is to integrate these widgets as angular directives. THE CONTROLLER $scope.widgets = ['one', 'two' ...

Troubleshooting a problem with jQuery: alter background color when checkbox is

I recently created a script to change the background color when a radio button is selected. While it works for checkboxes, I noticed that when another radio button is selected, the previous one still remains with the selected color. <script type="text/ ...

Is there a way to bring in data from a .d.ts file into a .js file that shares its name?

I am in the process of writing JavaScript code and I want to ensure type safety using TypeScript with JSDoc. Since it's more convenient to define types in TypeScript, my intention was to place the type definitions in a .d.ts file alongside my .js fil ...

Using vuex-class to interact with Vuex in non-Vue components

Is it possible to access Vuex outside of a Vue component using vuex-class? In a typical scenario, the process is quite straightforward: // some JS file import store from './../store'; // path to Vuex store store.commit('ux/mutationName&ap ...

Accessing a PDF document from a local directory through an HTML interface for offline viewing

As I work on developing an offline interface, I'm encountering an issue with displaying a PDF file when clicking on an image. Unfortunately, the code I have in place isn't working as intended. Can someone please assist me with this problem? Below ...

The jQuery Ajax Error is consistently being triggered

I'm puzzled as to why my custom callback error function keeps getting triggered. When I remove this callback function, the success callback works just fine. Some sources online suggest that it could be an encoding issue, but I don't think that&a ...

Need help implementing the disableGutters property on MTableToolbar?

I am currently using react material-table and I would like to customize the default toolbar styles by passing the prop disableGutters={true}, similar to how it's done in material-ui toolbar. Below is the code snippet that I have tried: <MaterialTab ...

Error message in Material-UI TextField not displaying when state is updated using Object.assign technique

Currently, I am facing an issue with validating a login form and displaying errors dynamically. These errors are passed as props from the child component. The problem arises when I set the errors object using Object.assign - the errorText does not show up ...

What is the reason for the request to accept */* when the browser is seeking a JavaScript file?

The html source appears as follows: <script type="text/javascript" language="JavaScript" src="myscript.js"></script> Upon debugging the http request using Fiddler, it is evident that the browser (Chrome) sends a GET request for myscript.js wi ...

Utilizing JQuery to merge variable identifiers

Imagine a scenario where the variables are structured this way: localStorage.var1a = 0; localStorage.varnum = 1000; Now, consider the following code snippet: for(x = 1; x < localStorage.varnum; x++){ if(localStorage.var.x.a > 0){ localStora ...

Utilizing the HTML button element within an ASP file combined with JavaScript can lead to the reloading of the

I am attempting to create a JavaScript function for an HTML button element. However, I have noticed that it causes the page to reload. Strangely, when I use an input with a button type, everything works perfectly. What could be causing this issue and why a ...

manipulating dropdown visibility with javascript

I'm feeling a bit lost on how to structure this code. Here's what I need: I have 5 dropdown boxes, with the first one being constant and the rest hidden initially. Depending on the option chosen in the first dropdown, I want to display the corres ...

Incorporating Past Projects into an Angular 2 Website

Some time ago, I built a Javascript game utilizing the HTML canvas element for image rendering. Now that I have a personal website created with Angular 2, I am unsure of how to properly embed my game into my site. Due to Angular 2 removing the script tag ...

Ways to remove a task in ReactJs agendas?

I am currently working on a code to delete an item from a list. However, I have encountered a problem where it is deleting items in a FIFO order instead of according to the index. export default class Todo extends Component{ constructor(){ supe ...

Aggregation in Mongodb - the power of processing data efficiently

{ "items": [ { "id": "5bb619e49593e5d3cbaa0b52", "name": "Flowers", "weight": "1.5" }, { "id": "5bb619e4ebdccb9218aa9dcb", "name": "Chair", "weight": "8.4" }, { "id": "5bb619e4911 ...

The communication between the extension and chrome.runtime.connect() fails, possibly due to an issue with the chrome manifest version

I've been working on converting a Chrome extension that stopped functioning in manifest version 2. I've removed inline JavaScript and switched from chrome.extension.connect to chrome.runtime.connect. However, I'm still encountering issues wi ...

Locate and modify a specific element within an array of objects

Currently, I am working with an array that looks like this: arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]. However, I need to add a condition to the array. If ...

Code-based document editing with CouchBase

To test Couchbase, I need to create a servlet that will edit 1,000 JSON documents by changing the value of '"flag": false' to '"flag": true'. How can I achieve this task? Here is my view code for finding documents with '"flag": fa ...

Guide on transmitting data from a child component to a parent object in Vue.js?

When I attempt to utilize a child component with custom form inputs and emit those values to the parent component, I encounter an issue where one input value disappears when another input value is entered. Let me showcase some code: Child Component <tem ...