创建永不匹配的mongo表达式的最佳方法 [英] Best way to create a mongo expression that never matches

查看:96
本文介绍了创建永不匹配的mongo表达式的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找的某种程度上等同于SQL:

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

WHERE 1 = 0

我正在寻找这样的东西,因为我正在构建一个类型安全的DSL来在我的域上执行查询,并支持合取和析取.有时候,添加一个从不匹配任何内容的查询可能比在代码中处理它更容易.

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.

例如,在我的用例中:

StampleFilters().underCategoryIds(sharedCategoryIds.toList)

在这种情况下,由于sharedCategoryIds为空,因此无法正常工作,因此导致查询为$(),该查询不过滤任何内容. 对于空列表,我宁愿构建一个从不返回任何内容的查询.

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?

我可能可以添加一些查询,例如{ somefield: unexistingvalue },但我想知道是否还有更好的方法.

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

修改

我希望该表达式是可组合的.我的意思是,它应该在类似$or(exp1,exp2,exp3)的查询中起作用,其中exp1表示从不匹配的表达式.

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)

推荐答案

我认为实现所需目标的最佳方法是添加{_id : -1}

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

db.coll.find({a : 1})将转换为db.coll.find({a : 1, _id : -1}).这比所有shx2解决方案都简单(除了最后一个带有noScan的解决方案,这很好).

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).

而且_id字段已经是主索引,因此它将很快意识到集合中没有这样的_id字段.

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

PS (如果要聪明地将其_id命名为-1),则可以执行{_id : NaN}. 如果出现_id = NaN,则您很可能需要重新开发您的应用.

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.

这篇关于创建永不匹配的mongo表达式的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆