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}]
You can use this aggregation query:
root using $objectToArrayk, so you can sort by that field.db.collection.aggregate([
{
"$set": {
"root": {
"$objectToArray": "$$ROOT"
}
}
},
{
"$sort": {
"root.k": 1
}
},
{
"$project": {
"root": 0
}
}
])
Example here