MongoDB 不等于
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9790878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB not equal to
提问by Akshat
I'm trying to display a query in MongoDB where a text field is not '' (blank)
我试图在 MongoDB 中显示一个查询,其中文本字段不是 ''(空白)
{ 'name' : { $not : '' }}
However I get the error invalid use of $not
但是我得到了错误 invalid use of $not
I've looked over the documentation but the examples they use are for complicated cases (with regexp and $not
negating another operator).
我查看了文档,但他们使用的示例用于复杂的情况(使用正则表达式并$not
否定另一个运算符)。
How would I do the simple thing I'm trying to do?
我将如何做我想做的简单事情?
回答by om-nom-nom
Use $ne
-- $not
should be followed by the standard operator:
使用$ne
-- $not
后面应该跟标准操作符:
An examples for $ne
, which stands for not equal:
的一个例子$ne
,它代表不等于:
use test
switched to db test
db.test.insert({author : 'me', post: ""})
db.test.insert({author : 'you', post: "how to query"})
db.test.find({'post': {$ne : ""}})
{ "_id" : ObjectId("4f68b1a7768972d396fe2268"), "author" : "you", "post" : "how to query" }
And now $not
, which takes in predicate ($ne
) and negates it ($not
):
现在$not
,它接受谓词 ( $ne
) 并否定它 ( $not
):
db.test.find({'post': {$not: {$ne : ""}}})
{ "_id" : ObjectId("4f68b19c768972d396fe2267"), "author" : "me", "post" : "" }
回答by Martin Konecny
If you want to do multiple $ne
then do
如果你想做多个$ne
然后做
db.users.find({name : {$nin : ["mary", "dick", "jane"]}})
回答by Kemal Fadillah
Use $ne
instead of $not
使用$ne
代替$not
http://docs.mongodb.org/manual/reference/operator/ne/#op._S_ne
http://docs.mongodb.org/manual/reference/operator/ne/#op._S_ne
db.collections.find({"name": {$ne: ""}});
回答by nilsi
From the Mongo docs:
来自Mongo 文档:
The
$not
operator only affects other operators and cannot check fields and documents independently. So, use the$not
operator for logical disjunctions and the$ne
operator to test the contents of fields directly.
该
$not
操作仅影响其他运营商不能独立检查字段和文件。因此,使用$not
运算符进行逻辑析取,使用运算$ne
符直接测试字段的内容。
Since you are testing the field directly $ne
is the right operator to use here.
由于您正在直接测试该字段,$ne
因此在这里使用正确的运算符。
Edit:
编辑:
A situation where you would like to use $not
is:
您想使用的一种情况$not
是:
db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
That would select all documents where:
这将选择所有文档,其中:
- The price field value is less than or equal to 1.99 or the price
- Field does not exist
- 价格字段值小于等于 1.99 或价格
- 字段不存在
回答by user3806115
If there is a null
in an array and you want to avoid it:
如果null
数组中有 a并且您想避免它:
db.test.find({"contain" : {$ne :[] }}).pretty()
回答by Andy
Real life example; find all but not current user:
现实生活中的例子;查找所有但不是当前用户:
var players = Players.find({ my_x: player.my_x, my_y: player.my_y, userId: {$ne: Meteor.userId()} });