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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With