"Discover a more efficient way to generate a single query, rather than multiple queries, from a single collection

Here is the structure of my collection:

{
    "_id" : "Pd2fl7xcT3iWEmpAafv4DA",
    "slot" : 1,
    "stat" : [
        {
            "unitStat" : "5"
            "value" : 13
        },
        {
                "unitStat" : "18",
                "value" : 1.96
        },
        {
                "unitStat" : "28",
                "value" : 1373
        },
        {
                "unitStat" : "41",
                "roll" : 2,
                "value" : 69
        }
    ]
}

I am interested in retrieving the top 5 sorted objects (based on any unitStat) for each slot.

Initially, I attempted to make individual calls to the database for each slot, but this approach proved inefficient. Subsequently, I experimented with aggregation for a single slot:

db.collection.aggregate( 
    {
        `$match`: {
            slot: 1,
            secondaryStat: {
                `$elemMatch`: {
                    unitStat:'5'
                }
            }
        }
    },
    {
        `$unwind`: `'$secondaryStat'`
    },
    {
        `$match`: {
            'secondaryStat.unitStat' : '5'
        }
    },
    {
        `$sort`: {
            'secondaryStat.value': -1
        }
    },
    {
        `$limit`: 5
    }
)

Is it possible to retrieve the top 5 sorted objects from a combination of 6 different slots?

Answer №1

Execute the below query to retrieve the desired output:

db.collection.aggregate([
        {
                $unwind:"$stat"
        },
        {
                $match:{
                        "stat.unitStat":"5"
                }
        },
        {
                $sort:{
                        "slot":1,
                        "stat.value":1
                }
        },
        {
                $group:{
                        "_id":"$slot",
                        "slot":{
                                $first:"$slot"
                        },
                        "stat":{
                                $push:"$stat"
                        }
                }
        },
        {
                $project:{
                        "_id":0,
                        "slot":1,
                        "stat":{
                                $slice:["$stat",0,5]
                        }
                }
        }
]).pretty()

Explanation of Aggregation Stages:

  • Stage I: Break down the stat array into individual documents
  • Stage II: Filter the data based on unitStat value of "5"
  • Stage III: Arrange the data in ascending order by slot and stat value
  • Stage IV: Group the data by slot and compile filtered stats into an array named 'stat'
  • Stage V: Limit the stat array length to 5

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

Creating a canvas element within an iframe: A step-by-step guide

I have a unique situation where I have an iframe containing a DIV element named "pageContainer1". My goal is to insert a canvas element into that specific DIV and then be able to access it in order to draw something on it. Despite my attempts so far, this ...

Implement a sleek carousel within a Vue component

Hello, I am trying to add a single slick carousel component to a block that already contains 2 components in a template. However, when I do this, it distorts the images of the other component. <template v-if="isMobile"> <vue-slic ...

Having trouble launching the freshly developed Angular app

I'm encountering an issue with my newly created app - I can't seem to launch it. Error: The loader “C:/C#/Angular/my-app/src/app/app.component.css” is not providing a string as expected. https://i.sstatic.net/6Xjwd.png https://i.sstatic.ne ...

Can you explain the distinction between admin.firestore.Timestamp.now() and admin.firestore.FieldValue.serverTimestamp()?

Learn more about the servertimestamp function in Firebase Firestore Explore how to use the now function in Firebase Firestore Timestamp I'm confused about the distinction between these two functions. Can someone clarify? Specifically, what advantag ...

Ways to specify the specific option within a select field

Here is my question: <select name="currency" id="currency"> <option value="AUD"&lgt;AUD</option> <option value="BDT"&lgt;BDT</option> <option value="EUR"&lgt;EUR</option> & ...

"Exploring the realms of AngularJS through callback functions and variable scopes

I am currently experiencing an issue with JavaScript in general. Specifically, I am trying to update a list after invoking a callback from two separate files. Here is the description of the callback : this.modify = function(){ var self = this; v ...

Dynamic array filtering in MongoDB Compass

I need help filtering MongoDB based on the given JSON format to only return records with serviceCountry = US under gfcidGlobals. Other objects should be ignored. The desired output is the gfcidGlobals data and details associated with the serviceCountry. J ...

Lost, a lone figure... beyond salvation

Help! I am encountering these errors while validating my code with W3C Line 41, Column 143: Oops! Stray end tag body. …t1_02.gif','images/Part1_03.gif','images/Part1_04.gif','images/Part1_05.png')"> ✉ Line 41, C ...

Utilize JQuery to modify hover state when focused and restrict tab navigation to specific areas on the keyboard

I'm currently working with a JQgrid in one of my projects (Check out the JFiddle here). and I have some specific requirements: 1.) I want the save & cancel button to become highlighted when a user tabs to it, similar to how it behaves on mouse ov ...

unable to access the undefined resource

Currently working on building my personal portfolio using HTML, CSS, and JavaScript. I have implemented transition animations that work smoothly until clicking on another hyperlink triggers the transitions properly but results in a blank page with the erro ...

Incorporated asynchronous functionality, struggling to integrate it into the code

Previously, I used to utilize the following code for handling state: //get state MyClass.prototype.getState = function(key) { var value; switch(this._options.type){ case "cookie": value = $.cookie(key); ...

Guide on how to retrieve information from an API and populate it into a dropdown menu

Currently, I am developing an MVC application that interacts with an API. My goal is to call a specific method from the API in order to populate data into a combo-box. However, as a newcomer to this technology, I am unsure of the best approach to take. An ...

What is the best way to incorporate both images and text in PHP code?

I'm currently working on creating a large image call-to-action (CTA) for my new WordPress website. I've set up a new field group with the type "group" in ACF, and added some functions in PHPStorm. However, none of my images, text, or links are ap ...

Can React provide custom styling to a specific segment of text before displaying it?

I'm looking to create a pokemon search box that offers suggestions of pokemons as the user types. It's working fine so far, but I also want to highlight the searched text when displaying the entire pokemon name. Basically, I want to replace the ...

Unable to retrieve ajax responseText within a jquery function

Seeking assistance with a form designed for user registration. Utilizing jQuery and AJAX to validate email address availability upon blur event. Employing e.preventDefault(); in JQuery code to prevent form submission in case of errors. However, encounterin ...

Mathjax2 in React is not supported in React v17

After successfully running recat-matcjax2 on react 16, I encountered some issues when updating to react version 17. I am facing two specific errors: These are the error files: https://i.sstatic.net/iy0ZV.png https://i.sstatic.net/trfrL.png Here is my ...

Incorporate issues into the VeeValidate error collection using the parent component, then monitor them from the child components

Is there a way to implement data transfer from a parent component to a child component for error handling? Specifically, how can I add data to the errors bag from the parent component and then listen to a specific error in the child component to display so ...

How to print a Base64 encoded file with the Print.js library

I am facing an issue with printing a Base64 file. Despite my efforts, the file does not print as expected. function convertToBase64() { var selectedFile = document.getElementById("inputFile").files; if (selectedFile.length > 0) { var fi ...

The issue with scrolling in the Chrome app arises when a fixed element is present, causing the scroll

I am experiencing an issue with my chrome app. The main window displays correctly, but the mouse scroll wheel does not work. Interestingly, when I open the main.html file in Chrome directly, the scrolling works perfectly fine. How can I troubleshoot and fi ...

I am experiencing difficulty with the button not responding when clicked, despite trying to implement JavaScript and the Actions syntax

Currently, I am in the process of automating form filling. After filling out the form, there is an update button that changes color instead of clicking when activated. This alteration indicates that the xpath is correctly identified. I have attempted two ...