How can i get sorted data in array by "name" in categories where ‘_id = 63fe948a22009cbbba53b905’?
My sample data:
{
"_id": "63fe948a22009cbbba53b905",
"options": {
"sort": "manual"
},
"categories": [
{
"priority": 0,
"options": "manual",
"name": "Nazwa 1",
"_id": "63fe8cc76d50062ae1f53821"
},
{
"priority": 0,
"options": "manual",
"name": "Inna-Nazwa",
"_id": "63fe8cc76d50062ae1f53822"
},
{
"priority": 0,
"options": "manual",
"name": "Nowa",
"_id": "63fea35cbbbaf3053ad1b25f"
},
{
"priority": 0,
"options": "manual",
"name": "Ihahaowa",
"_id": "63fea38118acd0f4d9ad4cac"
}
],
"updatedAt": "2023-03-01T01:10:49.817Z"
}
Result (sort data):
{
"options": {
"sort": "manual"
},
"categories": [
{
"name": "Ihahaowa",
"_id": "63fea38118acd0f4d9ad4cac"
},
{
"name": "Inna-Nazwa",
"_id": "63fe8cc76d50062ae1f53822"
},
{
"name": "Nazwa 1",
"_id": "63fe8cc76d50062ae1f53821"
},
{
"name": "Nowa",
"_id": "63fea35cbbbaf3053ad1b25f"
}
]
}
Sorry, but this is my beginnings with MongoDB. I has tried but it doesn’t work:
await NotesModel.findOne({ _id: id }, { 'options': 1, 'categories.name': 1, 'categories._id': 1, '_id': 0 }, {'categories.name': 1})
Thanks in advance for your help.
2
Answers
Sorting an array within a document is not supported in a projection, so you won’t be able to use findOne for that.
You could use aggregation with 3 stages:
for version 5.2 above
https://mongoplayground.net/p/S3P4WtU8hTi
for lower version
try it on https://mongoplayground.net/p/S3ZAXEcHdku