Guide to locating and organizing multiple fields in various documents within MongoDB and aggregating them into a unified array

In the header, the issue is clearly defined. I have a collection called "results" containing multiple documents:

{
    "_id" : "item_e4a2086048057ac9",
    "home" : "FH>87218379012",
    "username:" : "Jon Doe",
    "Apps" : {
        "game" : {
            "InVals" : {
                "ET" : {
                    "et1" : 1,
                    "et2" : 88,
                    "et3" : 7,
                    "et4" : 0.68,
                    "et5" : 5253,
                    "et6" : "7233-AL",
                    "et7" : "23-PL",
                    "et8" : "791-GY"
                }
            },
            "OutVals" : {
                "ET" : 74.00
            }
        }
    },
    "PAT" : 74
}

Next document:

{
    "_id" : "item_a90a2086048057ac9",
    "home" : "FH>87218379012",
    "username:" : "Jon Doe2",
    "Apps" : {
        "game" : {
            "InVals" : {
                "ET" : {
                    "et1" : 0,
                    "et2" : 9,
                    "et3" : 96,
                    "et4" : 3218,
                    "et5" : 6,
                    "et6" : "65-AL",
                    "et7" : "265-PL",
                    "et8" : "4-GY"
                }
            },
            "OutVals" : {
                "ET" : 4.00
            }
        }
    },
    "PAT" : 4
}

And so on... Now I want to retrieve all "PAT" fields from specific documents where the "home" field equals "FH>87218379012", then sort them in descending order and store them in an array variable like this:

var resultsArray = [74, 4....,n];

If necessary, I am open to solutions that involve storing each "PAT" value in a separate variable, sorting them individually, and later compiling them into an array. Ultimately, I need all "PAT" values from documents with "FH>87218379012" as their "home" field in descending order in an array.

Is this achievable without modifying my collection?

Answer №1

If you need to find and sort by a specific field in MongoDB, you can utilize an aggregation pipeline. Start by using the aggregation framework to match your desired criteria, then instruct MongoDB to sort by that field. Finally, use the $group stage along with the $push operator to gather the sorted values into an array.

db.coll.aggregate([
    {
        $match: {
            home: "FH>87218379012"
        }
    },
    {
        $sort: { PAT: -1 }
    },
    {
        $group: {
            _id: null,
            result: {
                $push: "$PAT"
            }
        }
    }
])

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

404 error occurs when attempting to load SVG files in Webpack 2

Recently, I delved into the world of webpack. However, I encountered a problem when trying to load an SVG file referenced in one of my CSS files. Despite trying various loaders such as this, that, and the other, I keep receiving a 404 error. Can anyone pro ...

Unable to establish connection to MongoHQ using Node.js connection URL

I have successfully set up and run a Node.js app using my local development MongoDB with the following settings and code: var MongoDB = require('mongodb').Db; var Server = require('mongodb').Server; var dbPort = 27017; v ...

Display or conceal a div element depending on the user's choice

I am looking to hide inactive divs, but whenever I reload the page, all tab contents merge into one. The screenshot below shows the issue I'm facing. Screenshot Below is the code snippet: $('.tab a').on('click', function ...

Looking for a way to add a permanent footer to the bottom of your webpage without affecting the tab order for accessibility?

I have a paginated form with a fixed navigation footer at the bottom that needs to stay in place even when scrolling. This footer should also be at the bottom of the page for mobile devices and tablets. To achieve this, I used position: fixed on the foote ...

Maintain the state of various panels on page load with the Bootstrap Accordion feature

I have implemented a Bootstrap accordion on my form page which allows users to open multiple panels simultaneously. Upon submitting the form, I want to preserve the state of any open Bootstrap accordion panels. To achieve this, I utilized code from stack ...

Content duplication within Three.js, React.js, and Next.js is a common issue

I've encountered a case where I am using Three.js in react(next js) and a Mesh I have created is duplicated multiple times import * as THREE from 'three'; function Index() { if (process.browser) { const scene = new THREE.Scene( ...

The Geolocation API popup on Safari for iOS kept appearing repeatedly

I have successfully implemented a code using the HTML5 Geolocation API to retrieve the user's current position within a mobile website. Although the code functions properly, there is an issue with Safari on iOS. Whenever the page is reloaded, a syste ...

Exploring the functionalities of AngularJS' ng-options when working with select elements

In my search through other posts, I came across this issue but couldn't find a solution. Here is the array in question: $scope.items = [ {ID: '000001', Title: 'Chicago'}, {ID: '000002', Title: 'New York' ...

PHP code to calculate the financial year array within a specified start and end date

For a PHP project using CodeIgniter, I need to retrieve all financial years between a given start date and end date. The financial year ranges from 01-04-2001 to 31-03-2002 (April to March). Example: public function getfinancialyears(){ $st ...

Accessing HTML partials from separate domains using AngularJS

I am looking to load html partials from Amazon S3 by uploading them and using the public URLs like this: 'use strict'; /* App Module */ var phonecatApp = angular.module('phonecatApp', [ 'ngRoute', 'phonecatAnimatio ...

Is it possible to utilize various providers in Next-Auth while still maintaining the same email address?

I am currently developing a Next.js application using NextAuth. At the moment, I have implemented login functionality with Google, credentials, and GitHub. However, I encountered an issue where if a user logs in with Google using the email "[email pro ...

Tips for implementing a smooth fade-in effect while rotating URLs within an iFrame

As I cycle through a list of URLs, I am displaying each one in an iFrame for a specific amount of time based on the corresponding value in the durations array. (function step(){ $j('.marquee').attr('src',urls[i].innerHTML); setTime ...

Variable indicating the number of items in the CollectionView section

In my project, I am attempting to nest a collectionView inside another collectionView. The tricky part is that the data I need to populate these cells is stored in an array of arrays, leading to variable counts for each parent cell. When implementing the ...

Dealing with Asynchronous JavaScript code in a while loop: Tips and techniques

While attempting to retrieve information from an API using $.getJSON(), I encountered a challenge. The maximum number of results per call is limited to 50, and the API provides a nextPageToken for accessing additional pages. In the code snippet below, my i ...

When scrolling, the fixed menu bar at the top of the page is making the content below jump

I am attempting to create a fixed submenu that sticks to the top of the page when scrolling, but I am encountering some issues. The current code I have is as follows: $(window).scroll(function () { if ($(window).scrollTop() > 175) { $('#loca ...

Inability to submit page after clicking on lower half of button while eliminating validations

In my current Struts2 application, I am encountering a issue related to validations on textfields. The validations include checks for missing values and incorrect values. Below these fields, there is a button that should submit the form once all validation ...

Obtaining a Buddypress user's name through a JavaScript file

When working with my buddypress PHP templates, I typically fetch the username of a user using their ID like this: <?php echo bp_core_get_username( '{{userID}}' ) ?> However, I now need to access the username from an external JavaScript fi ...

Display information in real-time based on user input using Highcharts

I am trying to display data using highcharts on my index.php page. Can anyone help me with this?, here is what I have attempted so far: This is the HTML code I have: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" cont ...

What are the issues with using AJAX in conjunction with a for-loop?

I'm currently developing a small application that needs to create work schedules and calculate hours: . I've written the function kalkulacja() to calculate the inputs for each row and output the results through ajax. However, I'm facing an i ...

Having trouble loading mtl file in Three.js with map_ks and bump instructions?

I am currently working with an MTL file that contains the following specifications: newmtl blinn_backSG illum 4 Kd 0.17 0.15 0.28 Ka 0.00 0.00 0.00 Tf 1.00 1.00 1.00 bump -s 0.1 0.1 canvas_specular.tif -bm 0.025 Ni 1.00 Ks 0.00 0.00 0.00 map_Ks -s 0.1 0.1 ...