Ambrosia
Ambrosia

Reputation: 88

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?

Upvotes: 3

Views: 2192

Answers (2)

Ambrosia
Ambrosia

Reputation: 88

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']   
       }
   }
}
])

Upvotes: 3

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

From what i can see, i think you want $let.

You can create local variable which can be used inside the $let expression.

Try this:

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

Here, you create local varialbes in vars expression, which can be used inside(and only inside in expression). I have created local_settles_bills, and local_overdue_bills, and which can be used in in expression with $$ as prefix.

I hope this helps you out.

Read MongoDb $let documentation for detailed information on $let.

Alternatively, you can do this as well :

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

Upvotes: 3

Related Questions