【问题标题】:mongodb how to query with nand operator?mongodb如何用nand运算符查询?
【发布时间】:2020-08-22 23:05:15
【问题描述】:

我正在使用 $match 聚合。 我试过了。

    $match : { 
      $not: {
      'A': false,
      'B': 'condition'
      } 
    } 

但不像 nand 那样工作。它的工作方式不像 A 而不是 B。 如何使用 Not(A and B) 查询?

【问题讨论】:

标签: mongodb operators


【解决方案1】:

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

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

    not ( A and B ) = not A or not B

使用 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"}}]})

使用 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"}}]}}])

【讨论】:

    【解决方案2】:

    这应该会为您获取结果

    {
        $or: [
            {'a': { $ne: 1} },
            {'b': { $ne: 2} }
        ]
    }
    

    但是,在我的情况下,这个表达式没有产生预期的结果,所以我尝试了这个-

    {
         $nor: [
           {
             $and: [
                 {a: 1},
                 {b: 2}
             ]
           }
        ]
    }
    

    【讨论】:

      【解决方案3】:

      有一个非常简单的技巧可以用 mongoDB 创建 NAND:

      $nor : { $and [..., ...] }
      

      【讨论】:

      • $nor 必须是数组,所以会出错。 mohakjuneja 的回答对我有用
      【解决方案4】:

      您可以在 mongodb 中使用可用选项以其他方式思考。

      db.Collection.find({'arrary.a':{$exists:false},'arrary.b':{$exists:false}})
      

      希望对你有所帮助...

      【讨论】:

      • 对不起,我无法理解。你能解释一下 $ 存在哪些角色吗?
      • 表示将生成那些没有字段A和B的文档。
      • 我的问题不是存在而是匹配特定值。
      • 所以你可以这样做 db.inventory.find( { A: { $ne: false },B:{$ne:condition } )
      猜你喜欢
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 2017-07-08
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多