Arranging files based on the total amount of a particular category within an array of related documents

Here is the structure of my main schema:

 _id: id,
 random: random, 
 cards: [objectId, objectId, ...]   //ref to cards

An example of a card in the schema:

 _id: id,
 random: random, 
 random: random,
 clicks: 15.

I am looking to sort the top schema based on the total number of clicks within the cards.

Answer №1

Instructions for Query1

  • To start, perform a lookup to do the left join, ensuring that the joined card documents are stored as an array (the join occurs if the array contains the card _id)
  • Next, sum up the clicks
  • Then, sort by the field that has the sum

*For descending order, use sort -1 instead of 1

Test query here

mainColl.aggregate(
[{"$lookup": 
   {"from": "cardCollection",
    "localField": "cards",
    "foreignField": "_id", 
    "as": "clickSum"}},
 {"$set": {"clickSum": {"$sum": "$clickSum.clicks"}}},
 {"$sort": {"clickSum": 1}}])

Steps for Query2

  • Similar to the previous query, but it performs the calculation before the join (slightly bigger code)

Test query here

mainColl.aggregate(
[{"$lookup": 
    {"from": "cardsCollection",  
      "localField": "cards",
      "foreignField": "_id",
      "pipeline": 
      [{"$group": {"_id": null, "clicksSum": {"$sum": "$clicks"}}}],
      "as": "clicksSum"}},
  {"$set": {"clicksSum": {"$arrayElemAt": ["$clicksSum.clicksSum", 0]}}},
  {"$sort": {"clickSum": 1}}])

Answer №2

After some experimentation, I ultimately settled on the following solution:

model.aggregate([ 
          {$lookup: {from: "cards", localField: "cards", foreignField: "_id", as: "cards"}},
          {$set: {clickSum: {$sum: "$cards.clicks"}}},
          {$sort: {clickSum: -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

How odd! Using window.location or location.replace redirects to the page and then reverses back!

While in debug mode, I am able to track which page is being accessed. Interestingly, whenever I use window.location or window.location.replace(..), the browser redirects to the specified page but then quickly returns to the original one! This strange beh ...

Interactive input field designed for modifying, adding, and removing data in MySQL

I am working on a project where I have a simple form. However, I need to dynamically change the form action from insert to update within the same page. Additionally, I also want to display the values on the same page. Within my code, I have set up the up ...

Having Trouble Adding Details to a New Cart for a User in Angular and MongoDB - What's Going On?

After working on an E-Commerce site for a while, I hit a roadblock. Despite taking a break and coming back with determination, I can't seem to resolve the issue at hand. The application features registration, login, product search, and a popup window ...

ValueError: Unable to perform slicing operation on this data

When attempting a query in nodejs, I encounter this error: [2017-08-19 19:06:55.946] [ERROR] error - TypeError: val.slice is not a function at escapeString (/var/www/Bot/node_modules/sqlstring/lib/SqlString.js:183:23) at Object.escape (/var/www/Bo ...

"Mastering the art of utilizing Async in combination with waterfall and Recursion in node

I've developed a script for transferring data from Dynamo to a MySQL database. Initially, I encountered performance issues on the SQL side due to not using asynchronous calls. To address this, I integrated the async library to throttle the Dynamo segm ...

Troubleshooting CORS Problem with AWS CloudFront Signed Cookies

I encountered an issue while implementing cloudfront signed cookies. When trying to access '' from '', the CORS policy blocked it due to absence of the 'Access-Control-Allow-Origin' header. This problem arose after rest ...

To handle a 400 error in the server side of a NextJS application, we can detect when it

I'm facing a situation where I have set up a server-side route /auth/refresh to handle token refreshing. The process involves sending a Post request from the NextJS client side with the current token, which is then searched for on the server. If the t ...

Using an array to set the center of a map - Google Maps API

I'm attempting to populate a HTML menu with values from a JavaScript multidimensional array using setCenter. Example of HTML Menu <li><a onclick="map.setCenter(cityList[0][1], cityList[0][2]); return false"><script>document.write( ...

How can you retrieve the preceding sibling using an Angular directive?

Currently, I am utilizing ELEMENTREF to interact with the DOM via Renderer2. Allow me to provide a simple example: import { Directive, Renderer2, ElementRef } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export c ...

Exploring the wonders of math in Angular with ng-repeat

Exploring the realm of mathematics within an angular expression, let's consider a scenario where a user can either have credit on the site or receive a percentage discount. Below is the code snippet in question: <div ng-repeat="item in NewArrivals ...

"Enhance your website with a sleek Bootstrap navigation system featuring dividers and

Need help with creating a Bootstrap nav menu similar to this design made in Photoshop? Wondering about the best way to position the logo and create dividers between menu items like shown in this image. Here's the HTML code currently being used: & ...

set up the router by defining the behavior for each route

My goal is to redirect the user back to the homepage when they click the browser's back arrow to return to the previous page. However, I'm facing an issue where I cannot go back to the previous page when I'm on the login page using the brow ...

Calculation Error in JavaScript/JQuery

I've been working on a JavaScript function to calculate the sum of values entered into textboxes, but it seems to be giving me inaccurate results in certain cases. Check out the FIDDLE here Enter values : 234.32 and 32.34 Result: 266.6599999999999 ...

Node.js - Passport authentication consistently results in redirection to failure route

I am currently working on creating a login form using passportJs, but I keep encountering the issue of failureRedirect. Despite searching on stack overflow for a solution, I have not found the correct answer yet. Below is my code: Here is how I am crea ...

What is the best way to add <li> to every element in an array?

I had a tough day today trying to figure out my code. My English isn't the best, so explaining my issue is hard. I decided to illustrate my problem in HTML and specify the kind of styling I need to achieve with JS. I also included an example using the ...

Clicking on a button in the Shield UI Grid Toolbar will apply filters to

Currently, I am working with a grid that utilizes a template for the toolbar. In this grid, there is a column labeled "Status." My goal is to filter the rows so that only those where the Status equals Request to Reschedule, Cancelled, Office Call Required, ...

I am facing an issue where I am unable to view JSON objects despite utilizing json2html library

Currently, I am facing a minor problem while trying to incorporate json2html into a project. Despite running the transform function successfully, it is not including the JSON objects as expected. In my setup, I execute a call to MongoDB, retrieving the JS ...

Experiencing memory issues while attempting to slice an extensive buffer in Node.js

Seeking a solution for efficiently processing a very large base64 encoded string by reading it into a byte (Uint8) array, splitting the array into chunks of a specified size, and then encoding those chunks separately. The current function in use works but ...

How can you verify the anticipated log output in the midst of a function execution with Jest unit testing?

Below is a demonstration function I have: export async function myHandler( param1: string, param2: string, req: Request, next: NextFunction, ) { const log = req.log.prefix(`[my=prefix]`); let res; If (param1 === 'param1&a ...

How can I add multiple filters to a Kendo Grid?

Is there a way to include two separate filter fields for date filtering in Kendo Grid UI? Currently, the method I am using only allows for one date filter to be displayed. filterable: { ui: function (element: any) { element.ken ...