Product SiteDocumentation Site

10.10. Ordered and Unordered Expressions

By default, the order in which a for clause binds its items is important.
This behaviour can be relaxed in order give the optimizer more leeway. An unordered expression relaxes ordering by for clauses within its operand scope:
Example 10.24. An unordered expression.
unordered {
  for $answer in collection("answers")
  where $answer.score ge 4
  count $c
  where $c le 2
  return $answer
}
Results:
{
  "_id" : "511C7C5D9A277C22D13880C3",
  "question_id" : 37823,
  "answer_id" : 37841,
  "creation_date" : "2008-09-01T12:14:38",
  "last_activity_date" : "2008-09-01T12:14:38",
  "score" : 7,
  "is_accepted" : false,
  "owner" : {
    "user_id" : 2562,
    "display_name" : "Ubiguchi",
    "reputation" : 1871,
    "user_type" : "registered",
    "profile_image" : "http://www.gravatar.com/avatar/00b87
a917ec763c0c051dc6b8c06f402?d=identicon&r=PG",
    "link" : "http://stackoverflow.com/users/2562/ubiguchi"

  }
}
{
  "_id" : "511C7C5D9A277C22D13880C4",
  "question_id" : 37823,
  "answer_id" : 37844,
  "creation_date" : "2008-09-01T12:16:40",
  "last_activity_date" : "2008-09-01T12:16:40",
  "score" : 4,
  "is_accepted" : false,
  "owner" : {
    "user_id" : 2974,
    "display_name" : "Rob Wells",
    "reputation" : 17543,
    "user_type" : "registered",
    "profile_image" : "http://www.gravatar.com/avatar/87692
81d99f8fe9c208fd6a926c383d1?d=identicon&r=PG",
    "link" : "http://stackoverflow.com/users/2974/rob-wells
",
    "accept_rate" : 94
  }
}

An ordered expression can be used to reactivate ordering behaviour in a subscope.
Example 10.25. An ordered expression.
unordered {
  for $question in collection("faqs")
  where exists(
    ordered {
      for $answer at $i in collection("answers")
      where $i eq 5
      where $answer.question_id
          eq $question.question_id
      return $answer
    }
  )
  return $question
}
Results:
{
  "_id" : "511C7C5C9A277C22D138808A",
  "question_id" : 4720508,
  "creation_date" : "2011-01-18T04:32:30",
  "last_activity_date" : "2011-01-19T06:46:34",
  "score" : 13,
  "accepted_answer_id" : 4720977,
  "title" : "Redis, CouchDB or Cassandra?",
  "tags" : [ "nosql", "couchdb", "cassandra", "redis" ],
  "view_count" : 5620,
  "owner" : {
    "user_id" : 216728,
    "display_name" : "nornagon",
    "reputation" : 3114,
    "user_type" : "registered",
    "profile_image" : "http://www.gravatar.com/avatar/13f27
199f9bf9c9f1261dc8a49630a6b?d=identicon&r=PG",
    "link" : "http://stackoverflow.com/users/216728/nornago
n",
    "accept_rate" : 86
  },
  "link" : "http://stackoverflow.com/questions/4720508/redi
s-couchdb-or-cassandra",
  "is_answered" : true
}