11

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

4
  • 1
    Please put some effort into properly tabbing your queries next time. They are super hard to read otherwise Commented Nov 26, 2015 at 17:10
  • Why are you trying not to use $ne? Is your condition going to be an array? If so, use $nin docs.mongodb.org/manual/reference/operator/query/nin Commented Nov 26, 2015 at 17:11
  • See also: docs.mongodb.org/manual/reference/operator/aggregation/not Commented Nov 26, 2015 at 17:15
  • 1
    This was just an example of a query I needed today. I know that in the future I will encounter much more difficult queries to negate and I know by experience that sometimes expressing a query straightforward and then checking for its opposite is easier and faster that reversing the truth of each operator and operand. So if I want to $notmatch how would I write it in mongo query? Commented Nov 28, 2015 at 4:01

2 Answers 2

18

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
    }
  }
])
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.