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}]

Answer

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