MongoDB using NOT and AND together

后端 未结 4 653
遇见更好的自我
遇见更好的自我 2021-02-02 10:53

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

4条回答
  •  别那么骄傲
    2021-02-02 11:24

    TLDR; You want a NAND Gate...

    db.getCollection('test').find({ $or: [ {institution_type:{$ne:'A'}}, {type:{$ne:'C'}} ]})
    

    ... And then go thank (upvote) this answer (not me)

    or a NOR Gate...

    db.getCollection('test').find({ $nor: [{institution_type:'A', type:'C'}] })
    

    Longer version...

    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'}] })
    

提交回复
热议问题