Master the art of MongoDB Aggregate with these simple steps!

Here is a sample data object:

[
  {
    "_id": "56bab”,
    "region": “AS”,
    “spentOn”: [
      “56bf623a0c90b5”
    ]
  },
  {
    "_id": "57bab",
    "region": "EU",
    "spentOn": [
      "b5”,
      "b6”,
      "b8”,
    ]
  },
  {
    "_id": "58bab",
    "region": "EU",
    "spentOn": [
      "b5”
      "b6”
    ]
  }
]

I am looking to create a MongoDB query (from JS) that will return the most common spentOn value based on a specified region. For instance, if I specify region='EU', I would like to receive back: b6, b5, and b8.

I have referenced this source for guidance and attempted the following code snippet, but I am unsure how to filter by a particular region:

return Q.promise(function(resolve, reject) {
   User.aggregate( [
        { $group: { _id: "$spentOn", count: { "$sum":1 } } },
        { }
    ] );
    resolve();
});

Any assistance on this matter would be greatly appreciated.

Thank you

Answer №1

As previously mentioned in the feedback, the key to solving this issue is utilizing the $unwind stage.

Here is a potential solution to address this:

db.users.aggregate([
    {$match:{
        region: "NA"    
    }},
    {$unwind:"$spentOn"},
    {$group:{
        _id: "$spentOn",
        count: {$sum:1}
    }},
    {$sort: {count:-1}}
])

Executing the above query will yield the following outcome:

{ "_id" : "b6", "count" : 2 }
{ "_id" : "b5", "count" : 2 }
{ "_id" : "b8", "count" : 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

Will a notification box appear upon submission indicating success or failure?

After the submit button is clicked, I need a pop-up box to display either a successful or failed message. Then confirm the message by clicking OK. Currently, I am seeing an "undefined" pop-up followed by a failed message pop-up. Can someone please assist m ...

Tabulator automatically inserted 'numrow' after retrieving the data

I have a table of undetermined information (consisting of various columns and rows). I am now at the point where I need to utilize the function table.updateData(), but this function specifically requires the column id to be present in the data structure. S ...

Tips for avoiding the default rendering of Nuxt 3 layout?

After reviewing the Nuxt 3 documentation and finding it lacking in explanation, I turned to the Nuxt 2 docs. According to them, the default layout should be replaced by a specific layout specified within the name property of the <nuxt-layout> compone ...

I am attempting to retrieve the JSON object value from an error response while making a POST request in my Next.js application

Users can input an email into an input field, which is then sent as a post request to an API using the following code: try { const res = await fetch("/api/email-registration", { method: "POST", headers: { ...

Is there a way to connect a Button to a different page in VUE.JS?

I currently have a button that needs to be linked to another page. This is the code I am working with at the moment. How can we write this login functionality in vue.js? It should direct users to the page "/shop/customer/login" <div class="space-x ...

What is the best way to send extra parameters to an ajax callback function?

Currently, I am implementing an ajax call in the following manner: util.AjaxCall(url, successCallbackFunction, errorCallbackFunction); function successCallbackFunction(result) { // Result returned from Ajax } Although everything is functioning correc ...

Encountering difficulties parsing XML using NodeJS (with ExpressJS) for MongoDB integration

I have a unique scenario where my data source is only available in XML format, whereas MongoDB prefers JSON. To work around this, I am attempting to adapt a method that currently handles JSON data to now process XML data instead. Below is the modified met ...

Using Bootstrap4 to merge rows into a single column or apply rowspan in Bootstrap

Hey there, I have a specific requirement that I need help with. Check out the image here. I want to enable the LCM information box when the LCM checkbox is checked. Below is my code: <div class="panel-body "> <div class="c ...

Is it possible to utilize AJAX to fetch code from a separate file, view, or page in order to create an experience akin to a single-page application

Essentially, I'm aiming to create a simplified version of a Single Page Application within the admin panel of my website. The idea is to organize the information by using tabs, making the panel less cluttered. Here's a rough layout of what I have ...

Learn how to dynamically alter the background color of a webpage by utilizing a JSON API for random color selection

My goal is to trigger a javascript function onload that will dynamically change the background color of the webpage using random colors fetched from a JSON file. ...

Retrieve selected value from HTML input with datalist and use it as an argument in a method

I have a datalist in my HTML input where I need to pass the selected value into JavaScript / Angular. It must be passed because the datalist is being used in an HTML table with multiple entries. Most examples I've come across show how to grab the valu ...

Designing a system that effectively handles subtract requests from clients on a server

When a server receives requests on '/subtract', it should accept two parameters, 'a' and 'b', and then return the difference between them as a plain text response. I have already set up the server and added the necessary requ ...

Using JavaScript to create customized checkboxes is a useful way to

I am looking to develop a JavaScript code that saves all the checkboxes selected by a user. When the user clicks on the finish button, the code should display what they have chosen (text within the label). Admittedly, I am unsure of how to proceed and wou ...

Regular expression to limit a string to a maximum of 5 consecutive numeric characters and a total of up to 8 numeric characters

I need help creating a regex pattern that limits a string to no more than 5 consecutive numeric characters and a total of 8 numeric characters. Here are some examples: 12345 => True Yograj => True Yograj1234 ...

Use Node-RED to fetch JSON or CSV data and store it in InfluxDB

Versions Node-RED v0.16.2 InfluxDB v1.2.2 Grafana v4.2.0 Ubuntu 16.04.2 I'm looking to access weather data from a local official weather station. The options available are in either csv or JSON format. I am attempting to retrieve the JSON feed us ...

What is the process for testing promise functions that contain an internal promise using Jasmine in an Angular environment?

In my service function, here's how it looks: asyncGetStuff: (id) -> stuff = [] @asyncGetItem id .then (item) -> #parse some data stuff.push data return stuff Now I am trying to verify the contents of 'stuff': ...

Is it possible to implement a route within a controller in Express.js?

In my controller, I currently have the following code: module.exports.validateToken = (req, res, next) => { const token = req.cookies.jwt; //console.log(token); if (!token) { return res.sendStatus(403); } try { const ...

Website errors appear on the hosted page in <body> section without being present in the code

Hello there, I have set up a debug website using my "Olimex ESP-32 POE" to send internal data via JSON, eliminating the need for Serial Output from the Arduino IDE (the reasons behind this are not relevant). #include "Arduino.h" #include <WiF ...

Is there an "AlphaNumeric" choice available for the AdonisJS 5 Validator?

Hello everyone, I just finished reading the documentation for Adonis JS and I couldn't find an option to validate an "alphanumeric" value. In AdonisJS 4.1, this option existed, but now that I'm trying to migrate to Adonis 5, I can't seem to ...

Having trouble with fetching data in React from a URL?

When attempting to send a post request to a specific URL without proxy settings, I encountered a CORS error. After setting up a proxy, the URL was still pointing to localhost. The error persists even after attaching my proxyfile.js and including the code s ...