Mario
Mario

Reputation: 35

MongoDB Aggregation Fields Addition

I need to have values modified as part of the aggregation framework in MongoDB.

Here below is my code: -

db.coln.aggregate(
{$match: {"year" : "2010","companyName" :/ABC/}},
{$unwind:"$hierarchy"},
{$unwind:"$hierarchy.Details" },
{
   $group:
    {   "_id": 
        {"companyName": "$companyName", 
        "year": "$year",
        "costHead": "$hierarchy.originalName"},
"total": { "$sum": "$hierarchy.Details.values" }}
},
{$project: {_id:0, "Firm":"$_id.companyName", "Year":"$_id.year","costHead":"$_id.costHead", "Total":"$total"}})

In the above aggregation framework. Here is my resultset: -

{Firm: "ABC", Year: "2010", costHead: "Mnfc", Total: 5000}

Now, results are fine except for the 3rd field - costHead: Mnfc. I would like to replace "Mnfc" with "Manufacturing".

I tried multiple ways of doing so.

  1. I tried using (cond and if) in the group section but that messes up the grouping.

  2. I tried using a cond and if in project but it just produces nothing since the $projection operator can only project what is passed on from previous levels and not generate it.

Out of ideas here. Any help would be apreciated.

Regards Mario

Upvotes: 0

Views: 84

Answers (1)

Volodymyr Synytskyi
Volodymyr Synytskyi

Reputation: 4055

Try again to use cond in the $projection. It seems to work fine for me:

{$project: {_id:0, "Firm":"$_id.companyName", "Year":"$_id.year",
  "costHead": { $cond: { if: { $eq: [ "$_id.costHead", "Mnfc"] }, then: "Manufacturing", else: "$_id.costHead" } }, 
  "Total":"$total"
}}

Upvotes: 1

Related Questions