Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore: How to get all documents where a specific field exist

I have a collection in Firestore where some documents contain an array but some don't. The structure looks like this:

document1 = {
    date: '2022-02-02',
    name: 'x',
    array: ['a'],
}   

document2 = {
    date: '2022-02-03',
    name: 'y',
} 

How can I get all documents where the field arrayexists? So in this example only document1?

Is any of these solutions possible:

db.collection('employees').where(`array`, '!=', null).get();
db.collection('employees').where(`array`, '>=', []).get();
like image 866
Dalon Avatar asked Oct 24 '25 16:10

Dalon


1 Answers

How can I get all documents where the field array exists?

When you add data to Firestore make sure to provide a null value for the array field like this:

document1 = {
    date: '2022-02-02',
    name: 'x',
    array: null,
}

In this way, the following query will work perfectly fine:

db.collection('employees').where(`array`, '!=', null).get();

If it's an ongoing project, and the array field doesn't exist at all, then simply update the existing documents with the array holding a null value. This is possible because null is a supported data type in Firestore.

like image 52
Alex Mamo Avatar answered Oct 26 '25 08:10

Alex Mamo