Search code examples
mongodbaggregateprojection

MongoDB Aggregation: $Project (how to use a field on the other field of the same projection pipeline)


This is what i want my aggregation pipeline to look, i just don't know how to properly do it

db.Collection.aggregate([
{
   $project: {
      all_bills: ‘$all_count’,
      settled_bills: { $size: ’$settled’ },
      overdue_bills: { $size: ‘$overdue’ },
      settled_percentage: { $divide: [‘$settled_bills’, ‘$overdue_bills’] }
   }
}
])

I want to use the "settled_bills" and "overdue_bills" fields inside the "settled_percentage" field on same projection pipeline. How to?


Solution

  • So i guess there is no way I can use fields on other fields that co-exist on same projection pipeline.

    (assume the settled_bills and overdue_bills consist not just the 'size' but with long query operators )

    I'll just do this instead, so i will not repeat the code on the $divide.

    db.Collection.aggregate([
    {
       $project: {
          all_bills: ‘$all_count’,
          settled_bills: { $size: ’$settled’ },
          overdue_bills: { $size: ‘$overdue’ },
       },
       $project: {
          settled_percentage: {
              $divide : ['$settled_bills','$overdue_bills']   
           }
       }
    }
    ])