What is the best way to arrange documents in mongoose using multiple fields?

Suppose I have a schema with two fields:

someDate: Date
isPriority: boolean

I want to create a sort query based on someDate, where records with isPriority: true are always prioritized first. How can this be achieved? Currently, I am able to sort by date as follows:

Record.find().sort({ someDate: -1 });

Answer №1

It appears that MongoDB has recently added support for sorting using key order, rather than just relying on index(es) to determine the sort.

According to MongoDB's official documentation, in order to achieve a "stable" sort, it is recommended to have a unique column as the last key in the query.

db.restaurants.find().sort( { "borough": 1, "_id": 1 } )

Therefore, for your specific query, you should use:

{isPriority: 1, someDate: -1, _id: 1}.

An incorrect approach would be:

{someDate: -1, isPriority: 1, _id: 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

Discover the exact location of an HTML element within an iframe

I am currently attempting to determine the position of an element that is within an iframe. I have written the following code for this purpose: // Custom function to calculate the position of an element on the page function getElementPosition(elem){ var ...

Unlocking the Power of arrayFilters in MongoDB for Efficient Pipeline-Style Updates

Currently utilizing Mongo 4.4, I am attempting to execute an update operation with the aggregation pipeline using updateOne to modify nested array elements. To target a specific array member for updating, I include an arrayFilter in the options. However, e ...

Error Alert: The index "dateform" is not defined

I have set up two calendar date pickers and am trying to obtain the input data or retrieve the "post" date. However, upon running my code, I am encountering the following error message: Notice: Undefined index: dateform I am puzzled by this error because ...

Layer one image on top of another image

I've been working on a website and I'm trying to overlay one image on top of another. Let me explain. Inside a td element with a width: 1101px, I have placed an image using the img tag (the logo of my website). The width of this image is 1101px. ...

What is the best way to determine the width of a div within a window that has been rendered using React?

I'm working on a task where I need to determine the size of a div (with CSS width set to 100%) and adjust the zoom factor of a component based on this size. The challenge arises during the initial run of the application when the div has not yet been c ...

"When attempting to upload an image from the front end, the issue arises that req.file

I have been troubleshooting this issue by referring to similar posts, but I am still facing the problem of getting 'undefined' when using console.log. I have followed instructions for defining the multer middleware from other sources, so I am uns ...

Vue js is throwing an error because it is unable to find the "buscador" property or method that is being referenced in the render function

I am currently diving into the world of laravel combined with Vue js. I am working on integrating a search engine using vue js components, and I would greatly appreciate any help you can provide. Thank you in advance. Below is the Vue js component where t ...

Is there a way to retrieve the quantity of children from an element using protractor?

I am currently working with Protractor and I need to determine the amount of child components associated with a specific element. The element in question belongs to a table category. let table = element(by.css('#myTable')); My objective now is ...

What could be causing my PHP Ajax file transfer to only display 000000 as the add on number?

After seeking assistance from stackoverflow, I am now only getting "000000" as the additional numbers: 1) My goal is to format ID2 to "000000" with six digits. For example, if the ID2 is 302, it should be displayed as "000302". 2) I want to merge the new ...

Create an interface that inherits from another in MUI

My custom interface for designing themes includes various properties such as colors, border radius, navbar settings, and typography styles. interface ThemeBase { colors: { [key: string]: Color; }; borderRadius: { base: string; mobile: st ...

Endless Google Locations Instances

My database entries are being displayed in a table using input fields. I want the Location field for each entry to be automatically completed using Google's API. HTML: <input name="edit_airplane[1][location]" type="text" class="airplane_location" ...

How can I access internal.Writable within the basic-ftp NodeJS module using TypeScript?

After examining the API documentation of the basic-ftp module, I came across the following: downloadTo(writableStream | localPath, remotePath, startAt = 0): Promise<FTPResponse> However, when utilizing the module in a TypeScript project, the method ...

Steps to generate an embedded array containing documents and subsequently create an embedded document for each element within

I have three databases in mongoDB with unique collections and corresponding documents: mosques, prayers, and subscriptions. Here is an example of each: Mosque Document: { "_id": "64a48ce14ebcac9ec9a3b0b9", "address": " ...

The process of implementing web-based online diagramming software involves a strategic approach to designing and integrating various

I'm really interested in learning how web-based online diagramming software works. If anyone could provide guidance or point me to example resources, I would greatly appreciate it. Here are some of the web-based online tools that I have been explorin ...

Unlocking the Correct Way to Retrieve JavaScript Class Properties

As I was creating a class constructor to manage my database, I found myself questioning the behavior of JavaScript along the way. To simplify things and understand the problem better, I stripped it down to its bare minimum. Here is the core of the issue: ...

Numerous toggles available for the mobile version

Hey there, I need some help! I have a footer navigation on my desktop website with 3 Ul elements. I want to turn each Ul into a toggle for the mobile version. Can anyone assist me with this? Thanks in advance! <footer class="footer"> <d ...

What are the steps for implementing timezone-js?

I found a project on GitHub that claims to convert one timezone to another. I've been trying to get it to work without success. After downloading and extracting the files, I created an HTML file with the following code: <html xmlns="http://www.w3. ...

Validation in Express. The property 'validatePassword' is not found within the type 'Document'

Recently, I started working with express and node.js to create an authentication system without a frontend. I am utilizing typescript, passport, passport-local, and mongoose in my project. However, I encountered the following errors: TSError: ⨯ Unable t ...

Tips for positioning elements in a way that prevents CSS fixed from overlapping upon page loading

Is there a way to adjust my navigation menu to prevent overlap upon page load, but have it overlap when scrolling down (Dynamic nav bar)? Check out my current setup: Upon initial page load, the navigation bar overlaps the text. I would like the navigatio ...

I am currently running a recursive loop to fetch data from MongoDB. However, the Express.js function runs through the entire script before the data can be successfully returned

Can someone assist me with setting up my Express route to handle the return of data from a recursive function that involves promises and fetching MongoDB data? Currently, my route is executing immediately without sending the data back to the client. The da ...