2

Does Firestore support something like whereNotEqual?

For example, I need to get exact documents where key "xyz" is missing. In Firebase realtime db, we could get it by calling *.equalTo(null).

Thanks.

Adam Zvada
  • 81
  • 4
  • 1
    My understanding of your question is that you want to query a collection to get all the documents that do not have an "xyz" field. Based on my reading of the documentation and experiments, I don't believe the Firestore API supports that. – Bob Snyder Nov 01 '17 at 22:01

2 Answers2

1

Firestore does not support a direct equivalent of !=. The supported query operators are <, <=, ==, >, or >= so there's no "whereNotEqual".

You can test if a field exists at all, because all filters and order bys implicitly create a filter on whether or not a field exists. For example, in the Android SDK:

collection.orderBy("name")

would return only those rows that contain a "name" field.

As with explicit comparison there's no way to invert this query to return those rows where a value does not exist.

There are a few work-arounds. The most direct replacement is to explicitly store null then query collection.whereEqualTo("name", null). This is somewhat annoying though because if you don't populate this from the outset you have to backfill existing data once you want to do this. If you can't upgrade all your clients you'll need to deploy a function to keep this field populated.

Another possibility is to observe that usually missing fields indicate that a document is only partially assembled perhaps because it goes through some state machine or is a sort of union of two non-overlapping types. If you explicitly record the state or type as a discriminant you can query on that rather than field non-presence. This works really well when there are only two states/types but gets messy if there are many states.

Gil Gilbert
  • 7,722
  • 3
  • 24
  • 25
0

Cloud Firestore now supports whereNotEqualTo in database queries.

Keep in mind if you have more than one field in your query you may have to create a composite index in Cloud Firestore.

Krisbenoit
  • 26
  • 3