29

How can I select all docs that do not have a certain field? I have the following structure:

user = {
    firstName: 'blabla',
    lastName: 'bloblo',
    address: {
        city: 'xxxx',
        state: 'xxx'
    }
}

I have tried comparing with null, but wasn't successful.

let db = firebase.firestore();  
let querySnapshot = await db
    .collection("users")
    .where("address", "==", null)
    .get();
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Ari
  • 7,251
  • 11
  • 40
  • 70
  • 1
    An empty field is not the same as a null field. Are you trying to query for a null value that's present in the document, or are you trying to query for a field that's completely missing? – Doug Stevenson Sep 20 '18 at 18:35
  • Completely missing – Ari Sep 20 '18 at 19:49
  • The question marked as duplicate is for Swift and the accepted solution there doesn't work. – Ari Sep 20 '18 at 19:51
  • One hidden point in that dup is that you can't query for fields that don't exist. You need some value to query for, even if it's just null. – Doug Stevenson Sep 20 '18 at 20:07

1 Answers1

33

Selecting "all docs that do not have a certain field" is not possible.

As you will learn by watching the very good Firestore video series called "Get to know Cloud Firestore" (https://www.youtube.com/playlist?list=PLl-K7zZEsYLluG5MCVEzXAQ7ACZBCuZgZ), in particular the 2nd video, queries in Firestore are based on indexes, and it is not possible to index on a field that is NOT in the document, or a field that does not have a certain value (i.e. a "not equal" operator).

However there is a workaround which consists in querying documents that contain properties with a null value data type, see How to query Cloud Firestore for non-existing keys of documents

Also interesting to note (even if it is not what you are asking for) is this technique for querying for values that are not null Firestore select where is not null

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • Just to add, I tried using "null" to checked if "deleted" existed. But instead I'm adding a property called "active" = true, and setting it to false when I mark my doc "deleted". That way I can use it in all my where clauses. – Michael Ozeryansky Apr 19 '20 at 06:48