What is the best way to arrange an array based on a specific field within a MongoDB document?

In my question document, I have a schema named QuestionSchema that includes fields such as title, body, user, category, comments, tags, image, and createdAt.

var QuestionSchema = new Schema({
    title: {
        type: String,
        default: '',
        trim: true
    },
    body: {
        type: String,
        default: '',
        trim: true
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    category: [],
    comments: [{
        body: {
            type: String,
            default: ''
        },
        root: {
            type: String,
            default: ''
        },
        user: {
            type: Schema.Types.ObjectId,
            ref: 'User'
        },
        createdAt: {
            type: Date,
            default: Date.now
        }
    }],
    tags: {
        type: [],
        get: getTags,
        set: setTags
    },
    image: {
        cdnUri: String,
        files: []
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
});

I am facing an issue where I need to sort the comments array by the root field. I attempted to manually sort the array at the backend and also tried using aggregation but was unsuccessful in sorting it. Can someone please provide assistance?

Answer №1

If you have a model object called Question in your code and you want to sort the "comments by "date" from createdAt, you can achieve this using the .aggregate() method:

Question.aggregate([
    { "$match": { "_id": docId } }, 
     { "$unwind": "comments" },
     { "$sort": { "_id": 1, "comments.createdAt": 1 } },
     { "$group": {
         "_id": "$_id",
         "title": { "$first": "$title" },
         "body": { "$first": "$body" },
         "user": { "$first": "$user" },
         "comments": { "$push": "$comments" },
         "tags": { "$first": "$tags" },
         "image": { "$first": "$image" },
         "createdAt": { "$first": "$createdAt" }
     }}],
 function(err,results) {
     // handle sorted results here
 });
 

However, if you don't need to aggregate across documents, it's simpler to just use JavaScript methods like .sort():

Quesion.findOneById(docId,function(err,doc) {
     if (err) throw (err);
     var mydoc = doc.toObject();
     mydoc.questions = mydoc.questions.sort(function(a,b) {
         return a.createdAt > b.createdAt;
     });
    console.log( JSON.stringify( doc, undefined, 2 ) ); // Nicely formatted output
});
 

In conclusion, while MongoDB provides tools for server-side sorting, it's often more efficient to do this on the client side when retrieving data unless aggregation across documents is necessary.

Both examples have been provided for reference.

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 can I retrieve a specific set of Firebase documents based on a property's value in a collection?

I'm currently developing a social media app using Firebase and React, and I need to implement a search bar that suggests users based on the input value. For example, when typing "F," I want to see suggestions like Foo and Bar, similar to common social ...

Can someone please provide me with a Javascript code snippet that accomplishes the same function

<script> document.addEventListener('DOMContentLoaded', function () { const menuItems = document.querySelectorAll('.headmenu li'); menuItems.forEach(function (menuItem) { menuItem.addEventL ...

Issue encountered during creation of a polyline in Cesium

When attempting to create a polyline in my ReactJs app using the code below, I encountered an error message stating "DeveloperError: Expected value to be greater than or equal to 0.0125, the actual value was 0." Can someone shed some light on why this er ...

What is the best way to utilize $.ajax for downloading JSON data from an HTML

I am currently facing an issue with a script that utilizes AJAX to retrieve JSON data. $.ajax({ type: "GET", url: url, /*url = index.html or data.json, many page use 1 script*/ success ...

Steps to generate an error in the 'response' function of a $httpProvider interceptor

I am currently working on creating a custom HTTP interceptor in Angular and I am looking to generate an error from the response of the $httpProvider interceptor. According to the provided documentation: response: Interceptors are triggered by the http re ...

Discovering the value of an item when the editItem function is triggered in jsGrid

Within my jsGrid setup, I have invoked the editItem function in this manner: editItem: function(item) { var $row = this.rowByItem(item); if ($row.length) { console.log('$row: '+JSON ...

Is there a way to generate a modal list of values by utilizing bootstrap and angular, while incorporating spring boot as the backend technology?

I'm working on developing a generic "List of Values" feature, which will be a searchable modal containing a natural identifier and description. I have successfully built an AngularJS application in Spring Boot to accomplish this task, but unfortunatel ...

I'm looking for assistance on programmatically adding or modifying the user-agent header in a Chrome browser using Selenium WebDriver. Can anyone help

Seeking assistance on programmatically adding or modifying the user-agent header for Chrome browser using Selenium WebDriver. File addonpath = new File("D:\\innpjfdalfhpcoinfnehdnbkglpmogdi_20452.crx"); ChromeOptions chrome = new ChromeOptions( ...

Checking for offline status in a Cordova app using Angular

I have implemented the following code to determine whether my Cordova application is online or offline. var networkState = navigator.connection.type; var states = {}; states[Connection.UNKNOWN] = 'Unknown'; states[Connection.ETHERNET] = ' ...

Looping through elements using jQuery in JavaScript

Is there a strange phenomenon happening with my variable in the HTML? I set it to "0", but it displays as "10" on the page. Despite using jQuery and JavaScript, the number stays static at "10" even after refreshing the page. I'm attempting to make th ...

Dynamically setting properties in a Vue component using Angular

After browsing through this interesting discussion, I decided to create a web component: <my-vue-web-comp [userId]="1"></my-vue-web-comp> Initially, everything was working smoothly in Angular when I assigned a static property. Howeve ...

How can I create an element in Javascript that does not inherit any CSS styles?

I'm creating a basic userscript with Greasemonkey for a school project that inserts a bright yellow box containing links onto all websites. Currently, my approach is straightforward: var guesses_div = document.createElement("div"); guesses_div.style. ...

Tips for updating the content of multiple tabs in a container with just one tab in Bootstrap 4.x

I am attempting to create two tab containers, where one is used to describe the content of a set of files and the other is used as a list of download links for the described files. Initially, I tried controlling the two containers using just one tab. I ca ...

Troubleshooting Issue: Unable to Display Dropdown Menu with Bootstrap 5 and ReactJS

Attempting to showcase a simple NavBar from the bootstrap documentation (https://getbootstrap.com/docs/5.0/components/navbar/) in React. I installed Bootstrap using npm I bootstrap. Here is the structure of my App: https://i.sstatic.net/h41mr.png Below ...

Display the element solely when the user enters a value greater than 0 into the input box

I am in the process of developing a WoW Classic statistics calculator that allows users to select a class and input various values. As the user makes changes to the inputs, the calculations are displayed below the form using vanilla JS and jQuery. I am ple ...

CSS- Strategically placing and centering images above specific keywords in (any) HTML content without disrupting the flow of text

My main objective involves dynamically inserting images above text on any given page using a content script. The challenge lies in maintaining the proper alignment of the text after adding the images. To achieve this, I surround the words where the image i ...

Prevent parent from scrolling when hovering over a div in HTML5

Unfortunately, the scrolling attribute is not supported in HTML5. I'm facing an issue where I have an svg inside an iframe within a div, and I need to enable scroll functionality within the div while preventing the page from scrolling at the same time ...

What is the best way to transform a JSON data-storing object into an array within Angular?

I am currently working on developing a machine learning model using tensorflow.js, but I have encountered a roadblock. The issue I am facing is that I have stored my JSON content in a local object, but for it to be usable in a machine learning model, I ne ...

Iterating through a JSON object and an array

I've been attempting to iterate through a JSON object but I'm struggling with it. Below is the JSON object I need to work with. This JSON data will be fetched from another website, and my goal is to loop through it to extract certain details. ...

Display only the objects in an array that match a specific value in MongoDB

Here is my current MongoDB Schema for the userTask: const userTaskSchema = new mongoose.Schema( { {...}{..}{...}{..} //Multiple objs above here, I'm specifically seeking assistance with the userTasks userTasks: [ // Arr ...