MongoDB сортировка вложенных элементов
Имею древовидную структуру вложенных массивов:
{
"message": "Success",
"data": [
{
"_id": "647ecc723c323c76a8ec8b50",
"children": [
{
"_id": "647ecc883c323c76a8ec8b53",
"indicators": [],
"mainCategorie": false,
"title": "Подпроцесс 1 Бизнес процесса 1",
"__v": 0,
"children": [],
"operations": [
{
"_id": "647ed7434e77ac4df6b962bf",
"children": [],
"operations": [],
"indicators": [],
"mainCategorie": false,
"title": "Операция 4 к Подпроцесс №1.",
"index": 2,
"__v": 0
},
{
"_id": "647ed73f4e77ac4df6b962bc",
"children": [],
"operations": [],
"indicators": [],
"mainCategorie": false,
"title": "Операция 3 к Подпроцесс №1",
"index": 0,
"__v": 0
},
{
"_id": "647ed7374e77ac4df6b962b6",
"children": [],
"operations": [],
"indicators": [],
"mainCategorie": false,
"title": "Операция 1 к Подпроцесс №1",
"index": 3,
"__v": 0
},
{
"_id": "647ed73b4e77ac4df6b962b9",
"children": [],
"operations": [],
"indicators": [],
"mainCategorie": false,
"title": "Операция 2 к Подпроцесс №1",
"index": 1,
"__v": 0
}
]
}
],
"operations": [],
"indicators": [],
"mainCategorie": true,
"title": "Бизнес процесс 1",
"__v": 0
},
{
"_id": "647ee6b2a585b43415d8d4ea",
"children": [],
"operations": [],
"indicators": [],
"mainCategorie": true,
"title": "Бизнес процесс 2",
"__v": 0
}
]
}
Необходимо у массивов operations сортировать значения по ключу "index".
Запрос у меня сейчас выглядит следующим образом:
export const getBusinessProcesses = async (req, res) => {
try {
let data = await BpTree.aggregate([
{
$match: {
mainCategorie: true,
},
},
{
$lookup: {
from: "b-processes",
localField: "children",
foreignField: "_id",
as: "children",
pipeline: [
{
$lookup: {
from: "b-processes",
localField: "children",
foreignField: "_id",
as: "children",
},
},
{
$lookup: {
from: "b-processes",
localField: "operations",
foreignField: "_id",
as: "operations",
},
},
],
},
},
{
$lookup: {
from: "b-processes",
localField: "operations",
foreignField: "_id",
as: "operations",
pipeline: [
{
$lookup: {
from: "b-processes",
localField: "operations",
foreignField: "_id",
as: "operations",
},
},
],
},
},
]);
return res.status(200).json({
message: "Success",
data,
});
} catch (err) {
return res.status(500).json({ err: err.message });
}
};
Простым добавлением { $sort: { index: 1 } } или $sortArray не обойтись. Если просто сделать запрос
let data = await BpTree.aggregate([{ $sort: { index: 1 } }]);
то массив сортируется, но само собой без древовидной структуры. Как я понимаю все дело во вложенности, но как правильно добавить в мою структуру, не могу понять. Буду признателен за любую помощь.
Источник: Stack Overflow на русском