Utilizing Mongoose aggregation for counting and grouping operations

I am trying to search for records that correspond to a specific URL but want to return a customized object instead.

Here is the model I am working with:

const ReactionSchema = mongoose.Schema({
  url: {
    type: String,
    required: true
  },

  emoji: {
    type: String,
    enum: ['happy', 'sad', 'angry'],
    required: true
  },

  ip: {
    type: String
  }
})

What I want to achieve is to query the model by matching the url and return a response structured like this:

[
  {
    "emoji": "happy",
    "count": 4,
    "reacted": true
  },
  {
    "emoji": "sad",
    "count": 9,
    "reacted": false
  },
  {
    "emoji": "angry",
    "count": 7,
    "reacted": false
  }
]

I need to dynamically determine if reacted is true or false by comparing the recorded ip with a variable I have in the process.

One approach I tried involved using:

.aggregate([
  {$match: {url}},
  {$group: {
    _id: '$emoji',
    count: {$sum: 1}
  }}
])

However, I am facing difficulties in combining the IPs and checking if my variable IP is present in that array or not.

Any assistance would be greatly appreciated. This is my first time seeking help!

Answer №1

Utilize the $push operator within the $group stage to generate an array of ip.

Include a $project stage to rename _id as emoji and to calculate the reacted field.

Use $setSubset to compare the previously calculated ips array with an input variable and return true if the input variable array is a subset of the ips array.

   aggregate([
      {$match: {url}},
      {$group: {
        _id: "$emoji",
        count: {$sum: 1},
        ips:{$push:"$ip"}
      }},
      {$project:{_id:0, emoji:"$_id",count:1, reacted:{ $setIsSubset: [[variableip], "$ips" ] }
      }}
    ])

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

Tips for incorporating line breaks into a contenteditable div using the key combination of ctrl + enter

$("#contenteditable").keydown(function(e) { var last = false; if (e.keyCode == 13) { if (e.ctrlKey) { let brNode = document.createElement('br'); let range = window.getSelection().getRangeAt(0); ...

Unraveling the mysteries of the Bootstrap carousel script

Hi everyone, I'm a newcomer to the world of JS and jQuery. Recently, while examining the code in carousel.js, I stumbled upon this particular line: this.cycle(true) The cycle function is structured like this: Carousel.prototype.cycle = function ...

Is it feasible to fetch numerous random, non-consecutive documents from MongoDB?

I am searching for a way to fetch a random selection of documents from my MongoDB database. After extensive research, I have come across methods that either retrieve one random document or a set of documents starting at a random skip position, but still in ...

Utilizing the MongoDB SDK for enhanced performance in NextJS serverside rendering

What do you think? I recently upgraded to NextJS 14 and started using the app router. One interesting thing I have is an image gallery on my website. The Gallery page is server-rendered for better performance. const Gallery = async () => { cons ...

Guide on utilizing fragment shaders from glslsandbox.com

I'm interested in experimenting with ShaderMaterial from Three.js, but I am not familiar with the OpenGL Shading Language. When I try to use the fragment shader code from the website mentioned above, I encounter a number of errors. I'm unsure if ...

Unable to view sidebar navigation on the screen

I've been experimenting with the sidebar navigation from w3 schools, specifically trying to create a side-nav that opens from one div. You can see an example here: http://www.w3schools.com/w3css/tryit.aspfilename=tryw3css_sidenav_left_right&stack ...

Manipulate a table using Jquery's find() method to insert a cell populated with information from an array using before()

My current challenge involves inserting a column of cells with data from an array. Despite attempting to use a for loop, all the cells end up displaying the same data from the array. What I really want is for each new cell to show 'row_header1', ...

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

Error in background request for Chrome app/extension, or problem allowing app to access Google Docs API

I'm encountering an issue where the Google Doc API is not allowing a desktop application to be installed, although this worked fine in Chrome 27.0 previously. Below is my Manifest.Json file: { "name": "__MSG_extName__", "description": "__MSG_ext ...

HTML link with "mailto:" not opening in a new tab

Just posted for the first time! I'm attempting to create a mailto link using 'templated' JavaScript that pulls specific data from a JSON object: var menu = { "menu": [ { "title": "let's talk", "link": "mailto:<a href ...

Utilize AJAX to fetch and display the response from a Node JS route directly onto an HTML page

At the moment, I am retrieving client-side HTML/JS inputs (var1 and var2) which are then sent to server-side Node JS. The input values are stored in variables through an AJAX post call made to a specific route. What I want now is to define the values of v ...

initiate colorbox resizing when parsley validation occurs

Currently, I am using parsley.js validation and colorbox to send a form via ajax. One issue I am encountering is determining how to dynamically resize the colorbox when validation errors appear. My goal is to activate this function when parsley detects er ...

Transferring data to a child component through Route parameters

Although I have come across numerous questions and answers related to my query, I still seem unable to implement the solutions correctly. Every time I try, I end up with an 'undefined' error in my props. Let's take a look at my parent compo ...

Tips on converting Django model into desired format for Bootstrap-tables plugin integration

I want to integrate the bootstrap-table plugin with server-side functionality using Django Rest Framework to populate the data on the table. However, I keep getting the message "No matching records found". After some investigation, I discovered that a spec ...

Gruntjs Live Reload is actively monitoring for changes, yet fails to refresh the page

Check out my Gruntfile.js here Also, take a look at my package.json here I ran npm install in the main directory of my workspace (using WAMP) and it created a node_modules folder along with several subfolders. After navigating to the directory c:\w ...

An error occurred: Reaching the maximum call stack size when utilizing the .map function in jQuery

Encountering a console error: Uncaught RangeError: Maximum call stack size exceeded This is the jQuery snippet causing trouble: $(document).on("change","select.task_activity", function(){ selected_activity = $("select.task_activity :selected").map(fu ...

When trying to run a jQuery function on click or load events, an error message stating that

When I have an .on(click) event triggering an ajax call, I want the same actions to occur when the page loads as well. My idea is to create a function that contains everything within the .on(click) event and trigger this function on page load. Although I ...

Troubleshooting problem with printing iframes on Firefox

When attempting to print an iframe with a large amount of data using the code below, I'm encountering an issue in Firefox where only the first page is printed. The rest of the pages are not being included in the printout. window.frames[frameID]. ...

Injecting services differently in specific scenarios in AngularJS

I have a unique angular service called $superService that I utilize across many of my directives and controllers. However, there is one specific directive where I want to implement the following behavior: If another directive utilizes $superService in its ...

Tips for stopping the textarea from moving around as you type and avoid it hitting the bottom of the page: Utilize JQuery and

As I type into the auto-sizing textarea, the text runs to the bottom of the page and causes it to dance uncontrollably with each key press. This forces me to constantly scroll down to see what's happening. How can I prevent this page dancing and keep ...