Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda