Pascal DeMilly
Pascal DeMilly

Reputation: 731

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

Upvotes: 11

Views: 16854

Answers (2)

igmrrf
igmrrf

Reputation: 559

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

Upvotes: 0

davidhilton68
davidhilton68

Reputation: 331

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
    }
  }
])

Upvotes: 18

Related Questions