TomBomb
TomBomb

Reputation: 3296

Why can't I use $nin, $exists, etc. inside a Mongo pipeline match?

I've looked high and low for this answer and nothing has worked. I have a pipeline query with a match term like this:

$match: {
  $expr: {
    $and: [
      ....
    ]
  }
}

Inside the $and I have all sorts of conditions using $eq, $in, $ne, $gt, $lt, etc.

However try as I may I can't get it to recognize $nin or $exists. I'm trying to add a term where I search for a key not existing, eg:

{ $exists: [ '$key', 0 ] }

I keep getting

MongoError: Unrecognized expression '$exists'

and

MongoError: Unrecognized expression '$nin'

Can anyone help??

Upvotes: 5

Views: 4166

Answers (1)

Ashh
Ashh

Reputation: 46461

You can only use aggregation operators inside the $expr and the $nin and $exists are query operators not aggregation ones. Use the above conditions outside the $expr expression.

Something like

{ "$match": {
  "key": { "$exists": true },
  "$expr": {
    "$and": [
      {...}, {...}
    ]
  }
}}

Upvotes: 6

Related Questions