Reputation: 169
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?
Upvotes: 3
Views: 5355
Reputation: 12420
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} ...}
Upvotes: 3
Reputation: 147314
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]}});
Upvotes: 5