Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Sorting without considering null values

In js with node js i want to sort result from model without considering document with nil values for example Products = [ {_id:ObjectID(), priority:3},

{_id:ObjectID(), priority:1},

{_id:ObjectID(), priority:2},

{_id:ObjectID()} ]

So this mongo schema so i need a query to find sorted element witjout considering nil but documemts with nil values must be at the end of results in both ascending or deacending order

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

So here is an example assuming your data is in a collection called "products". Here we assume the null value is expected to sort at the end of the results. Also, it is assumed you wish to sort priority in an ascending fashion.

I use an arbitrary large number - 999999 - to represent null values and sort by that value.

Aggregation

db.products.aggregate([
    {
        $addFields:
        {
            "sortField":
            {
                $ifNull: [ "$priority", 9999999 ]
            }
        }
    },
    {
        $sort: { "sortField": 1 }
    },
    {
        $project: { "sortField": 0 }
    }
])

Results

[
  { _id: ObjectId("61b0e373c6c466d7d1ea9b5b"), priority: 1 },
  { _id: ObjectId("61b0e373c6c466d7d1ea9b5c"), priority: 2 },
  { _id: ObjectId("61b0e373c6c466d7d1ea9b5a"), priority: 3 },
  { _id: ObjectId("61b0e373c6c466d7d1ea9b5d") }
]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!