Is it possible to query firebase for documents in a collection where the number of elements in an array of a particular field is greater than 0
For my example, each document has-a field called 'people', which contains an array of integers (or the array is empty).
My search always return 0 documents, but I have documents that I can see when I search in the firestore database admin panel.
import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';
admin.initializeApp();
var db = admin.firestore();
export const helloWorld = functions.https.onRequest(function(req,res)
{
var all_users = db.collection('users');
var query = all_users.where("people.length", ">", 0).get().then(snapshot =>
{
let docs = snapshot.docs;
//return 1st document found
res.send(docs[0].data());
});
query.catch(error =>
{
res.status(500).send(error);
});
});
This is not possible with Firestore. The only things you can query for array type fields is the exact contents of some element in the array.
Your alternative for filtering on the size of any array is to use an integer field to record the number of elements in the array, and keep it in sync with changes to that array.
Indexes are sparse in FS so you can simply do an orderBy and only return documents with populated data on the ordered property:
.collection("users").orderBy("people", "asc")
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