how to get corresponding values of fields by passing a map object in $project stage in mongodb aggregation

27 Views Asked by At
let departmentsMap = {
  '1576996323453': 'QA',
  '1874996373493': 'Dev',
  '1374990372493': 'BA',
  '1874926373494': 'Tech Support',
}

Above is my sample departments map object. I am running an aggregation pipleine on employees collection where each document has a department field, whose value is the id of corresponding departments(keys in the above onject). now i want to project as below

{
  $project:{
      department :   // i want get the department name here. data is there in local variable
    }

}

immediate help will be appreciated

1

There are 1 best solutions below

0
Joe On

You could use $switch for that.

Assuming the field name in the document is "department", that might look like:

{$project: {
   department: { $switch: {
       branches: [
         {case: {$eq: ["$department", "1576996323453"]}, then: "QA"}
         {case: {$eq: ["$department", "1874996373493"]}, then: "Dev"}
         {case: {$eq: ["$department", "1374990372493"]}, then: "BA"}
         {case: {$eq: ["$department", "1874926373494"]}, then: "Tech Support"}
       ],
       default: "$department"
}}