Home > OS >  How to return the result of a previous pipeline stage into a new field
How to return the result of a previous pipeline stage into a new field

Time:12-18

I have this function that returns an array of Institution info:

const getInstitutionsInfo = async () => {
  const sum_current_students = {
    $addFields: { number_of_current_students: { $size: "$current_students" } },
  };
  const sort_by_largest_number_of_current_students = {
    $sort: {
      number_of_current_students: -1,
    },
  };
  
  const pipeline = [
    sum_current_students,
    sort_by_largest_number_of_current_students,
  ];
  const response = await Institution.aggregate(pipeline);
  return response;
};

The result is an array:

[Institution_1_data, Institution_2_data ... ]

where each Institution_X_data is an object.

I would like to add another stage to the pipeline in the end that would make the final result like this:

{
  result: [Institution_1_data, Institution_2_data ... ]
}

I tried different combinations of $reduce but I couldn't achieve that result.

CodePudding user response:

Add $group stage

{
  "$group": {
    "_id": null,
    "result":{
      "$push" : "$$ROOT"
    }
  }
}

MongoPlayground | System Variables


const getInstitutionsInfo = async () => {
  const sum_current_students = {
    $addFields: { number_of_current_students: { $size: "$current_students" } },
  };
  const sort_by_largest_number_of_current_students = {
    $sort: {
      number_of_current_students: -1,
    },
  };
  const group_students = {
    $group: {
      _id: null,
      result: {$push: "$$ROOT"}
    }
  };
  
  const pipeline = [
    sum_current_students,
    sort_by_largest_number_of_current_students,
    group_students
  ];
  return await Institution.aggregate(pipeline);
};
  • Related