MongoDB aggregation divide array element by non-array element

Hello,

so I have an aggregation pipeline, with this group as a stage.

I’ve put arrows at lines of interest

stage_group_month = {
        "$group" : { 
            "_id": { 
                "year": "$_id.year", 
                "month": "$_id.month"
            },
--->        "total_project_cost" : { "$sum": "$project_cost" },
            "total_hours": { "$sum": "$project_durationNumber"},
            "total_salaries": {"$sum": "$salaries"},
            "projects": { 
                "$push":  {
                    "_id": "$_id.projectId",
                    "name": "$projectName",
--->                "cost": "$project_cost",
                    "duration": "$project_durationNumber",
                    "salaries" : "$salaries",
                    "gross_profit": {"$subtract": [ "$project_cost", "$salaries" ]}
                }
            }
        }
    }

and I just want to do

stage_add_percentage_revenue = {
        "$addFields":
        {
            "projects.percentage_revenue" : {"$divide": ["$projects.cost", "$total_project_cost" ]}
        }
    }

If I replace “$projects.cost” by some number like 100 I have a result. But I can’t access project.cost.

How can I do that ?

The field projects is an array, and you want to calculate percentage_revenue for each of the projects. For this you need to use the $map aggregate array operator. This will allow iterate over the array field and calculate the percentage_revenue for each of the projects, i.e., array element’s.

@Prasad_Saya was right, $map was the way to go. More information to https://stackoverflow.com/questions/73465964/mongodb-aggregation-divide-array-element-by-non-array-element

This topic can be deleted as it a dupplicate

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.