MongoDB using NOT and AND together

后端 未结 4 644
遇见更好的自我
遇见更好的自我 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:25

    You're looking for NOT (A AND C), which is equivalent to NOT A OR NOT C:

    db.collection.find({
      "$or": [
        {"institution_type": {"$ne": "A"}},
        {"type": {"$ne": "C"}}
      ]
    })
    

    MongoDB also has a $nor logical operator that "performs a logical NOR operation on an array of one or more query expression and selects the documents that fail all the query expressions in the array", so an equivalent query would be:

    db.collection.find({
      "$nor": [
        {"institution_type": "A"},
        {"type": "C"}
      ]
    })
    

    The accepted answer recommends using a $where operator, but that is unnecessary here and taxes performance.

提交回复
热议问题