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

96
Views
Looking for a way to sort data by key in MongoDB

I was trying to use GET request to get data from MongoDB, but the order of data is changed every time I refresh the URL. I used the $sort method in MongoDB, but the order is still changed.

let apiURL_1 = await axios.get('http://localhost:3000/Mydata');

My data:

[{"Bread":6},{"Fruit":6},{"Cholate":4}]

Expected Output (alphabet order) either using $sortaggregation from MongoDB or doing some javascript to sort data.

[{"Bread":6}, {"Cholate":4}, {"Fruit":6}]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use this aggregation query:

  • First create a field called root using $objectToArray
  • Then, the keys are in a field called k, so you can sort by that field.
  • And last remove the auxiliar field created previously.
db.collection.aggregate([
  {
    "$set": {
      "root": {
        "$objectToArray": "$$ROOT"
      }
    }
  },
  {
    "$sort": {
      "root.k": 1
    }
  },
  {
    "$project": {
      "root": 0
    }
  }
])

Example here

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!