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

Time:02-17

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();

CodePudding user response:

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.

CodePudding user response:

First of all you should try your solutions.

If they dont work, you can try to loop through your documents and check if doc.data().array exists

  • Related