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 $sort
aggregation from MongoDB or doing some javascript to sort data.
[{"Bread":6}, {"Cholate":4}, {"Fruit":6}]
CodePudding user response:
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