Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you negate a $match aggregate in mongodb

I have the following query that I need to find the reverse.

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

I an trying not to use

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

What I would really like is to use $not: [ condition ] as I will have more difficult aggregations to write. However I cannot find the right syntax. Any help appreciated. I am using mongodb 3.0.7

like image 809
Pascal DeMilly Avatar asked Nov 26 '15 16:11

Pascal DeMilly


1 Answers

I think this is essentially what you mean (apologies if $not)

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

  {
    $project: {
      customer_id: 1,
      lastTransactionDate: 1,
      currentBalance: 1,
      status: 1
    }
  }
])
like image 188
davidhilton68 Avatar answered Oct 11 '22 05:10

davidhilton68