mongodb如何使用nand运算符进行查询?

you*_*ang 5 operators mongodb

我正在使用 $match 聚合。我尝试过这个。

    $match : { 
      $not: {
      'A': false,
      'B': 'condition'
      } 
    } 
Run Code Online (Sandbox Code Playgroud)

但不像nand那样工作。它的工作方式类似于 not A and not B。我如何使用 Not(A and B) 进行查询?

小智 6

这应该会给你带来结果

{
    $or: [
        {'a': { $ne: 1} },
        {'b': { $ne: 2} }
    ]
}
Run Code Online (Sandbox Code Playgroud)

然而,这个表达式在我的例子中没有产生预期的结果,所以我尝试了这个 -

{
     $nor: [
       {
         $and: [
             {a: 1},
             {b: 2}
         ]
       }
    ]
}
Run Code Online (Sandbox Code Playgroud)


小智 4

$not 运算符不会反转复杂表达式。您需要使用 $and 或 $or 来表示复杂的表达式。

使用逻辑规则,我们知道以下内容是相同的:

    not ( A and B ) = not A or not B
Run Code Online (Sandbox Code Playgroud)

使用 MongoDB 查询语言,您将拥有:

db.collection.find({$or:[{"a":{"$ne":false}},{"b":{"$ne":"condition"}}]})

OR simplifying the double boolean:

db.collection.find({$or:[{"a":true},{"b":{"$ne":"condition"}}]})
Run Code Online (Sandbox Code Playgroud)

使用 MongoDB 聚合框架,您将拥有:

db.collection.aggregate([{"$match":{$or:[{"a":{"$ne":false}},{"b":{"$ne":"condition"}}]}}])

OR again, simplified to:

db.collection.aggregate([{"$match":{$or:[{"a":true},{"b":{"$ne":"condition"}}]}}])
Run Code Online (Sandbox Code Playgroud)