I\'m trying to negate an $and
clause with MongoDB and I\'m getting a MongoError: invalid operator: $and
message back. Basically what I want to achieve
db.getCollection('test').find({ $or: [ {institution_type:{$ne:'A'}}, {type:{$ne:'C'}} ]})
... And then go thank (upvote) this answer (not me)
db.getCollection('test').find({ $nor: [{institution_type:'A', type:'C'}] })
I couldn't find a logical operator in MongoDB to handle $nand
logic, so I "built" the logic (see below).
There is an open feature request for a $nand
operator, but I wouldn't hold my breath (created 2014).
$nor
can also do what you want, if you invert the $ne
logic.
(But IMO - it feels like we're bastardising the behaviour - only using the inverse $not
behaviour, and disregarding the $and
behaviour of the array... but it works, so it's not wrong).
db.getCollection('test').insertMany([
{ "institution_type" : "A", "type" : "C" },
{ "institution_type" : "A", "type" : "D" },
{ "institution_type" : "B", "type" : "C" },
{ "institution_type" : "B", "type" : "D" }
])
// "NAND gate": (NOT A) OR (NOT B) -> correct 3x results
db.getCollection('test').find({ $or: [ {institution_type:{$not:{$eq:'A'}}}, {type:{$not:{$eq:'C'}}} ]})
// or simpler...
db.getCollection('test').find({ $or: [ {institution_type:{$ne:'A'}}, {type:{$ne:'C'}} ]})
// or simpler still...
// "NOR gate": (NOT A) AND (NOT B) -> correct 3x results
db.getCollection('test').find({ $nor: [{institution_type:'A', type:'C'}] })