I'm working on a software that translates queries in the business domain into MongoDB query documents.
For this I need somethink like a "WHERE 0==1" clause for MongoDB, i.e. a query document that can be combined with $and
and $or
operators and behaves like a logical false
and can be optimized by the mongo query engine.
This way, if some subpart of the query builder detects an "impossible" condition, it could just return this "false" query document and let the mongodb engine ignore the respective branch of the query syntax tree.
{$where: "false"}
does the trick, but it seems that in this case the mongoDB engine evaluates "false" on every row of the result (instead of simply returning an empty result set).
I also came up with{_id: {$exists: false}}
, but an explain()
shows that the query still uses an index scan.
So I'm curious if there's any other option to obtain an empty result set.
Deeper Explanation
The user of my software will be able to define queries in a domain specific query language, which will be translated into a rather complex mongodb query document. This query will basically have the form of {$and: [ {$or: [ {},{$and: ...},...]}]}
, so this is a deeply nested, rather complex tree of conditions.
The construction of the tree is currently straightforward, since every element of the domain query translates more or less nicely into a corresponding Mongo query.
If there's one condition deep down the tree where the my software can decide on its own that it's always false I'd like to make this as explicit as possible to the Mongo query engine. So for instance, if all the "intermediate" documents consist of $and
operators (and thus the overal outcome of the query would be always "false"), I want the mongo engine to detect this as quickly as possible.
If I do this in SQL, the equivalent would be something like
SELECT * FROM TABLE WHERE C1 AND C2 AND (C3 OR C4) AND ... AND (1=0)
When the SQL engine gets this query, it doesn't need to consult any index or table at all, since the condition can be "proven" to always be false.