Uploaded image for project: 'Documentation'
  1. Documentation
  2. DOCS-13309

MongoDB does not guarantee short circuit evaluation and it should not be mentioned

      Description

      These pages:
      https://docs.mongodb.com/manual/reference/operator/query/and/
      https://docs.mongodb.com/manual/reference/operator/aggregation/and/

      mention that

      The $and operator uses short-circuit evaluation. If the first expression (e.g. <expression1>) evaluates to false, MongoDB will not evaluate the remaining expressions.
      

      and

      $and uses short-circuit logic: the operation stops evaluation after encountering the first false expression.
      

      Although there is a kernel of truth here and $and does perform short-circuit evaluation for performance, the query system is free to change the order of predicates inside a $and. In fact the find query system currently sorts all of them in an order that's arbitrary to the user in find. Agg performs some reordering in unusual circumstances.

      In general the query system must be free to reorder predicates as it sees fit during optimization and the order it chooses may change when MongoDB is upgraded or due to other factors.

      When the order is changed, the user will not get the short-circuit evaluation they specified in the query.

      I've opened a ticket to track a request for a way to optionally define predicate evaluation order: SERVER-45231. But for now it should be emphasized that there is no way to guarantee the order no matter what the query system empirically seems to be doing today. Following from this, we cannot guarantee that unnecessary $and expressions are evaluated or not evaluated at all. Also if a runtime error would occur due to the evaluation of an expression in a $and, we cannot guarantee it will or will not occur.

      This is true for find and aggregation and for predicates listed outside of a $and within a find query. If we're defensive about it in the docs we can prevent customer surprise later.

      Scope of changes

      Impact to Other Docs

      MVP (Work and Date)

      Resources (Scope or Design Docs, Invision, etc.)

            Assignee:
            jason.price@mongodb.com Jason Price
            Reporter:
            jacob.evans@mongodb.com Jacob Evans
            Votes:
            1 Vote for this issue
            Watchers:
            10 Start watching this issue

              Created:
              Updated:
              Resolved:
              2 years, 33 weeks, 2 days ago