Arranging group collection post query using aggregation operations

When I use the aggregate function to get all users with the same name, the results returned by the API are not sorted even though I specify to sort by the 'name' field.

const aggregateQuery: any = [
            { $group: { _id: '$name', count: { $sum: 1 }, users: { $push: '$$ROOT' } } },
            { $match: { count: { $gt: 1 } } },
            { $unwind: '$users' },
            { $replaceRoot: { newRoot: '$users' } },
            { $sort: { name: 1 } }
        ];`

        const users = await this.userRepository.getModel().aggregate(aggregateQuery).exec();

Despite my efforts, the order of the records remains unsorted.

Answer №1

To achieve a case-insensitive sort, follow these steps:
For example, if you require the fields name and age,

Consider using the following query :

[ { "$project": { "name": 1, "age" : 1, "insensitive": { "$toLower": "$name" } }},{ $group: { _id: '$name', count: { $sum: 1 }, users: { $push: '$$ROOT' } } }, { $match: { count: { $gte: 1 } } }, { $unwind: '$users' }, { $replaceRoot: { newRoot: '$users' } }, { $sort: { insensitive: 1 } } ]

If there are additional fields to include in the output, use the query below instead.

[ { "$project": { "name": 1,   createdAt : 1 }},{ $group: { _id: '$name', count: { $sum: 1 }, users: { $push: '$$ROOT' } } }, { $match: { count: { $gte: 1 } } }, {"$addFields":{"users.insensitive": { "$toLower": "$_id" },}}, { $unwind: '$users' }, { $replaceRoot: { newRoot: '$users' } }, { $sort: { insensitive: 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

"Utilize a custom filter in AngularJS to narrow down data based on specified numerical

Can anyone assist me in creating a filter for AngularJS data? I have two inputs, minAgeInput and maxAgeInput. I want to retrieve all products/objects (using ng-repeat) where the product's minimum age and maximum age fall within the limits set by the ...

What could be the reason for receiving [object object] from a JSON response?

Utilizing the datatables plugin, I am in need of refilling the table with ajax. To achieve this, I populate the table columns with the data retrieved from an ajax file (in json format) as shown in the following code snippet: $.get(select.data('url&a ...

Adding an iframe with inline script to my Next.js website: A step-by-step guide

For my Next.js project, I have this iframe that needs to be integrated: <iframe class="plot" aria-label="Map" id="datawrapper-chart-${id}" src="https://datawrapper.dwcdn.net/${id}/1/" style="width: ...

"Positioning a div around a Bootstrap form-inline: A step-by-step guide

When using Bootstrap 3 "form-inline" within a <div>, I noticed that the div seems to be nested within the form-inline. This is how my code looks: HTML <div class="wrapper"> <div class="form-inline"> <div ...

Problem concerning the window object in a React functional component

Hey there, I am currently facing a situation where I need to access the window object within my React component in order to retrieve some information from the query string. Here is an excerpt of what my component code looks like: export function MyCompone ...

Adjust the height of a div based on the font size and number of lines

I'm trying to create a function that automatically sets the height of a div by counting lines. I managed to get it partially working, but then it stopped. Can someone please help me with this? function set_height() { var div_obj=document.getEleme ...

React's memo and/or useCallback functions are not functioning as anticipated

Within my Home Component, there is a state called records, which I utilize to execute a records.map() and display individual RecordItem components within a table. function Home() { const [records, setRecords] = useState<Array<RecordType>>(l ...

Guide to fetching and displaying a complex array API using JavaScript's fetch method

Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API: fetch('https://datausa.io/api/data?d ...

Exploring Various Shapes in THREE JS

Currently, I am utilizing the EdgesGeometry for rendering my objects. I am currently exploring options on how to morph a Tetrahedron into an Octahedron, an Octahedron into a Box, a Box into a Sphere, and vice versa. Despite searching through numerous doc ...

Bring JavaScript Function into Vue's index.html File

Recently in my code files, I noticed the following: function example() { console.log("testing"); } In another file, I have something like this: <head> <script src="../src/example.js" type="text/babel"></sc ...

In AngularJS expressions, you can compare two dates and use ng-hide based on the comparison

Is it possible to compare two Date strings using Angular JS Expressions? HTML <body ng-controller="app"> <div>{{Today}}</div> <div>{{ItemDate}}</div> <div>{{ItemDate<Today}}</div> </body> ...

Discovering a CSS value using jQueryUncovering the CSS value with jQuery

Currently, I have a script that allows me to change the color of an event in a calendar to red when clicked. eventClick: function(calEvent, jsEvent, view) { $(this).css('border-color', 'red'); } Now, I want to enhance this featur ...

403 Forbidden Error encountered when attempting to incorporate JavaScript

I have encountered an issue with my code where I am trying to grab a form from another website. The PHP code in the header is meant to sanitize the GET string in the URL for security purposes. Essentially, I have a page called order.html which functions pr ...

What is the method for accessing 'this' beyond the scope of my object?

My Jcrop initialization for a website includes my own namespace. I have a question regarding the this keyword. Whenever I need to access my base object called "aps" in any callback function, I have to wrap this in a variable (I chose the word that). Is t ...

Develop a custom cell editor for ag-Grid and insert it into a designated location within

I am currently working with Angular 16 and AgGrid 30. My goal is to have the cell editor created in a different location than its default position, which is within a div element at the bottom of the body with these classes: ag-theme-material ag-popup. I w ...

A guide on validating dates in Angular Ionic5 with the help of TypeScript

I have tried multiple solutions, but none seem to work when validating the current date with the date entered by the user. The date is passed from the user into the function parameters, but how do I perform validation? How can I validate the date? isToday( ...

Creating a Form in a Popup with Bootstrap

I have implemented Bootstrap on my website. Check it out at: hubb.tekkkz.com I am facing an issue where, when clicking on the login/register button on the right, the modal pops up. However, the user input elements within the modal are not taking up the ful ...

What could be causing the partial to not load JavaScript properly?

Hello, I am a newcomer to Angular and I'm currently working on implementing the slick carousel. It functions properly on the index page, but when I try to use the same HTML in a partial and include it with ng-view, it doesn't work as expected. T ...

Navigating through tables and selecting rows

I am currently facing an issue with my HTML table that consists of 1000 rows and 26 columns. To navigate between rows and make selections, I have implemented a jQuery plugin on the table. The problem lies in the performance of the plugin, even with the la ...

Storing a MySQL query result in a global array in a Node.js environment

Just diving into the world of Node.js and Express, I'm trying to wrap my head around asynchronous functions and global variables. Specifically, I'm working on connecting to a MySQL database, fetching query results, and displaying them on a test.h ...