如何在mongodb中否定一个$match聚合操作

10

我有以下查询语句需要找到其反转形式。

db.contracts.aggregate([ 
    { $match: { currentBalance: { $gt: 0 }, status: 'open' } }, 
    { $project: { customer_id: 1, lastTransactionDate: 1, currentBalance: 1, status: 1 } }
])
我正在尽力不使用

$or: [ currentBalance: { $ne: 0 }, status: { $ne: 'open' } ]

我真正希望的是使用 $not: [ condition ] ,因为我需要编写更复杂的聚合操作,但我找不到正确的语法。非常感谢任何帮助。我正在使用mongodb 3.0.7。


1
请下次花点心思将查询语句正确地缩进。否则它们很难阅读。 - David says Reinstate Monica
你为什么不想使用 $ne?你的条件将会是一个数组吗?如果是,那就使用 $nin https://docs.mongodb.org/manual/reference/operator/query/nin/ - ʰᵈˑ
另请参阅:https://docs.mongodb.org/manual/reference/operator/aggregation/not/ - David says Reinstate Monica
1
这只是我今天所需查询的一个示例。我知道将来会遇到更困难的否定查询,也有经验证明有时直接表达一条查询语句,然后检查其相反面比翻转每个运算符和操作数的真值更容易、更快速。所以如果我想要$notmatch,我应该如何编写mongo查询? - Pascal DeMilly
2个回答

17

我认为这基本就是你的意思(如果不是,请原谅)

db.contracts.aggregate([
  {
    $match: {
      currentBalance: { $not: { $gt: 0 } },
      status: { $not: { $eq: 'open' } },
    },
  },

  {
    $project: {
      customer_id: 1,
      lastTransactionDate: 1,
      currentBalance: 1,
      status: 1
    }
  }
])

0

db.contracts.aggregate([ 
    { $match: { 
         currentBalance: 0, 
         status: { 
             $not: { 
                 $regex: 'open' 
             }
         }
     }
   }, 
   { $project: {
         customer_id: 1, 
         lastTransactionDate: 1, 
         currentBalance: 1, 
         status: 1 
     }
   }
])


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接