Using $not in mongodb

大兔子大兔子 提交于 2020-01-15 01:23:45

问题


I'm trying to do something like this :

select * from table where not (a=3 and b=4 and c=3 or x=4)

I would expect this to work:

db.table.find({
  $not: {
    $or: [
      {
        $and: [
          { a: 3 },
          { b: 4 },
          { c: 3 }
        ]
      },
      { x: 4 }
    ]
  }
})

But it gives me an error:

 error: { "$err" : "invalid operator: $and", "code" : 10068 }

Is there another way to express it in mongodb?


回答1:


Using { $not : { $and : []} } will not work ($not is not like other operators, can only be applied to negate the check of other operators).

$and is not the problem here, this also doesn't work (though without reporting any errors):

{ $not : {  a : {$gt : 14} }  

you'd have to rewrite it to

{ a : {  $not : {$gt : 14} }

Coming back to your query:

`not (a=3 and b=4 and c=3 or x=4)` 

is equivalent to:

a!=3 and b!=4 and c!=3 or x!=4

and that you can do in mongo:

{a : { $ne : 3}, b : { $ne : 4} ...}



回答2:


Firstly, I don't think you mean "and" as a field will never 3 and 4 at the same time - it can only be 3 or 4. So, assuming you do want "documents where b is not 3 or 4, then you can use $nin (not in) like this:

db.table.find({b:{$nin: [3,4]}});


来源:https://stackoverflow.com/questions/8893759/using-not-in-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!