$let operator and external variables(MongoDB)

$let Binds variables for use in the specified expression, and returns the result of the expression with Following syntax :

{ $let: { vars: { < var1 >: < expression >, … }, in: < expression > } }

From MongoDB Manual : $let can access variables defined outside its expression block, including system variables. If you modify the values of externally defined variables in the vars block, the new values take effect only in the in expression. Outside of the in expression, the variables retain their previous values. Click Here for more information.
Manual is not clear about how to define the variable externally? use var keyword in javascript or any other choice? I was also confused when I gone through this operator’s description in manual and trying here to give some more clarification on external variable binding in $let.

There is only limited ways to create a aggregation variable in MongoDB as of now.Apart form system variables users can only create variables in $let, $redact, $map operations.Variables defined in a $map or $redact can be referred within a $let, that is what they meant in MongoDB manual.

An example of using $map variable in $let :

A simple $map operator without $let

> db.grades.find()
  { "_id" : 3, "quizzes" : [ 3, 8, 9 ] }
  { "_id" : 1, "quizzes" : [ 5, 6, 7 ] }

//Using a simple $map:
db.grades.aggregate([{
  $project: {
    adjustedGrades: {
      $map: {
        input: "$quizzes",
        as: "grade",
        in: { $add: [ "$$grade", 2 ] }
      }
    }
  }
}]);

//Result:
{ "_id" : 3, "adjustedGrades" : [ 5, 10, 11 ] }
{ "_id" : 1, "adjustedGrades" : [ 7, 8, 9 ] }

Now defining a $let to use variable $$grade defined in this $map:

db.grades.aggregate([{
  $project: {
    adjustedGrades: {
      $map: {
        input: "$quizzes",
        as: "grade",
        in: {
          $let: {
            vars: { varin: "$$grade" },
            in: { $add: [ "$$varin", 4 ] }
          }
        }
      }
    }
  }
}]);

//Result:
{ "_id" : 3, "adjustedGrades" : [ 7, 12, 13 ] }
{ "_id" : 1, "adjustedGrades" : [ 9, 10, 11 ] }

Same way other aggregation variables can be used.

Note: If you modify the values of externally defined variables in the vars block, the new values take effect only in the in expression. Outside of the in expression, the variables retain their previous values.

Faisal K K

Software Engineer,Poet, Open source enthusiast,

India