问题描述
在SQL中,可以添加1 = 1或1 = 0查询条件以本质上分别返回全部或不返回记录.我如何在mongo中做同样的事情?
In SQL, it's possible to add a 1=1 or 1=0 query condition to essentially return all or no records, respectively. How can I do the same in mongo?
推荐答案
正如评论中所回答的,mongo中1=1
查询条件的等效项是使用空对象{}
作为查询.例如,db.foos.find({})
.
As answered in the comments, the equivalence of a 1=1
query condition in mongo is to use the empty object {}
as the query. For example, db.foos.find({})
.
通过将空数组传递给$in
查询条件,可以在mongo中模拟1=0
查询条件.例如,db.foos.find({ _id: { $in: [] } })
.此外,使用在$where
查询条件下始终返回false的javascript函数也可以.例如,db.foos.find({ $where: function() { return false } })
.
A 1=0
query condition can be simulated in mongo by passing an empty array to the $in
query condition. For example, db.foos.find({ _id: { $in: [] } })
. Additionally, using a javascript function that always returns false in a $where
query condition works as well. For example, db.foos.find({ $where: function() { return false } })
.
与{ _id: 0 }
或{ _id: null }
相比,这两个条件对于1=0
的附加好处是,即使0
或null
是集合中_id
的有效值,它也将起作用.但是,我不确定这两个查询中的任何一个是否会带来额外的性能损失.
The added benefit of these two conditions for 1=0
compared to { _id: 0 }
or { _id: null }
is that it will work even if 0
or null
are valid values for _id
in your collection. However, I am not sure if either of these queries may carry additional performance penalties.
这篇关于如何在mongo中查询1 = 1或1 = 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!