Firestore select where is not null

Solution 1:

Update Sep 2020: v7.21.0 introduces support for not equals (!=) queries! That means you can now use the code bellow:

firestore.collection('employees').where(`equipments.${equipm‌​entId}`, '!=', null)

Previous answer:

Firestore has no "not equal" operator. But looking at the logic, what you're trying to do is query for values which are String, and not null. Firestore can do that if you pass a String to the where() function.

So what you can do is query for values lower than \uf8ff. That's a very high code point in the Unicode range. Since it is after most regular characters in Unicode, this query will return everything that is of type String:

firestore.collection('employees').where(`equipments.${equipm‌​entId}`, '<', '\uf8ff')

Or you can simply query for values higher than "" (empty String):

firestore.collection('employees').where(`equipments.${equipm‌​entId}`, '>', '')

Solution 2:

FWIW since Firestore indexes are sparse [1] you can do something like:

firestore.collection('employees').orderBy(`equipments.${equipm‌​entId}`)

And you'll only get documents where that field is set. If you're explicitly setting the fields to null in your database, however, you'll get null values first, so if you want to avoid explicit null values you can do:

firestore.collection('employees').orderBy('equipments.${equipm‌​entId}').startAfter(null);

[1]: Sparse in the sense that if the field is not present in the document, Cloud Firestore does not create an index entry in the index for that document/field.