Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore select where a field is null [duplicate]

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();
like image 231
Ari Avatar asked Sep 20 '18 18:09

Ari


1 Answers

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

like image 157
Renaud Tarnec Avatar answered Nov 07 '22 09:11

Renaud Tarnec