Product SiteDocumentation Site

10.6. Let Clauses

Let bindings can be used to define aliases for any sequence, for convenience.
For each incoming tuple, the expression in the let clause is evaluated to a sequence. A binding is added from this sequence to the let variable in each tuple. A tuple is hence produced for each incoming tuple.
Example 10.18. A let clause.
for $answer in collection("answers")
let $qid := $answer.question_id
group by $question := $qid
let $count := count($answer)
where $count gt 1
return {
  "question" : $question,
  "count" : $count
}
Results:
{
  "question" : 6183352,
  "count" : 2
}
{
  "question" : 4419499,
  "count" : 2
}
{
  "question" : 37823,
  "count" : 2
}

Note that it is perfectly fine to reuse a variable name and hide a variable binding.
Example 10.19. A let clause reusing the same variable name.
for $answer in collection("answers")
let $qid := $answer.question_id
group by $qid
let $count := count($answer)
where $count gt 1
let $count := sum(
  collection("faqs")
    [ $$.question_id eq $qid ]!size($$.tags)
)
return {
  "question" : collection("faqs")
      [$$.question_id eq $qid].title,
  "count" : $count
}
Results:
{
  "question" : "Find CouchDB docs missing an arbitrary fiel
d",
  "count" : 4
}
{
  "question" : "MySQL and NoSQL: Help me to choose the righ
t one",
  "count" : 4
}
{
  "question" : null,
  "count" : 0
}