Попробуйте для группировки данных:
db.collection.aggregate([
{
$group: {
_id: {
planId: "$planId",
processId: "$processId"
},
strategies: { $addToSet: "$strategyId" }
}
},
{
$group: {
_id: "$_id.planId",
planId: { $first: "$_id.planId" },
processes: {
$addToSet: {
processId: "$_id.processId",
strategies: "$strategies"
}
}
}
}
]);
С сортировкой:
db.collection.aggregate([
{ $sort: { "strategyId": -1 } },
{ $sort: { "processId": 1 } },
{
$group: {
_id: {
planId: "$planId",
processId: "$processId"
},
strategies: { $addToSet: "$strategyId" }
}
},
{
$group: {
_id: "$_id.planId",
planId: { $first: "$_id.planId" },
processes: {
$addToSet: {
processId: "$_id.processId",
strategies: "$strategies"
}
}
}
}
]);
С учетом других коллекций:
db.collection.aggregate([
{ $sort: { "strategyId": -1 } },
{ $sort: { "processId": 1 } },
{
$lookup:
{
from: "BusinessProcess",
localField: "processId",
foreignField: "id",
as: "BusinessProcesses"
}
},
{
$lookup:
{
from: "RecoveryStrategy",
localField: "strategyId",
foreignField: "id",
as: "RecoveryStrategy"
}
},
{
$group: {
_id: {
planId: "$planId",
processId: "$processId",
processData: { $arrayElemAt : ["$BusinessProcesses" , 0] },
},
strategies: { $addToSet: "$RecoveryStrategy" }
}
},
{
$group: {
_id: "$_id.planId",
planId: { $first: "$_id.planId" },
processes: {
$addToSet: {
processId: "$_id.processId",
processData: "$_id.processData",
strategies: "$strategies"
}
}
}
}
]);