Aggregation operator for "is not null"

Looking through the list here: https://www.mongodb.com/docs/atlas/atlas-search/operators-and-collectors/
I don’t see any operators that could be used to query if a field is “not null” (or “not equal” to null). Am I mistaken?

Hi,

Since null is a valid value, you can leverage operator $ne:

db.collection.aggregate([
  {
    "$match": {
      "field": {
        "$ne": null
      }
    }
  }
])

Working example

4 Likes

Hi @Francesca_Ricci-Tam,

This is not directly available within the $search stage to my knowledge. There’s also the associated feedback engine post for your request which you can vote for in the meantime.

You could possibly perform the $search stage first as per normal followed by a $match stage using the $ne operator (As Nenad has mentioned) if it suits your use case although I do understand that this would not make use of any indexes (for the $match stage that’s after the $search stage).

Regards,
Jason

4 Likes

Thanks @NeNaD and @Jason_Tran – indeed, using a $match right after the $search stage is exactly what I ended up doing in the end. : )
I realized that I was approaching it the wrong way – I shouldn’t be trying to filter on non-text parameters inside the $search stage (which would be primarily for text-based searching).

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.