Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create a mongo expression that never matches

Tags:

mongodb

What I am looking for is somehow the equivalent of doing in SQL:

WHERE 1 = 0

I'm looking for such a thing because I'm building a typesafe DSL to perform queries on my domain, supporting conjunctions and disjunctions. Sometimes it may be easier to add a query that never match anything, instead of dealing with it in the code.

For exemple, in my usecase:

StampleFilters().underCategoryIds(sharedCategoryIds.toList)

In this case, it does not work as expected because sharedCategoryIds is empty, so it results in a query being $(), which does not filter anything. For an empty list, I would rather build a query that never returns anything.

Is there an easy way to do such a thing, without any impact on performances?

I could probably add some query like { somefield: unexistingvalue } but I wonder if there is nothing better.

Edit

I expect the expression to be composable. I mean it should work in queries like $or(exp1,exp2,exp3) where exp1 is for exemple the expression that never match.

If you have any proposition, it would be nice to explain why one is better than others and how it affect the query engine performances (or not)

like image 577
Sebastien Lorber Avatar asked May 28 '14 16:05

Sebastien Lorber


1 Answers

I think the best way to achieve what you want is to add {_id : -1}

db.coll.find({a : 1}) will be transformed into db.coll.find({a : 1, _id : -1}). This is simpler then all shx2 solutions (except of the last one with noScan which is nice).

Moreover _id field is already a primary index, so it will quickly realize that there is no such _id field in the collection.

P.S. if someone would be so smart to name their _id as -1, then you can do {_id : NaN}. If there will be _id = NaN then you most probably need to redevelop your app.

like image 148
Salvador Dali Avatar answered Sep 19 '22 14:09

Salvador Dali