Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query firebase for documents that contain an array of length > 0

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

});
like image 234
aman Avatar asked Mar 21 '19 19:03

aman


2 Answers

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.

like image 102
Doug Stevenson Avatar answered Oct 13 '22 00:10

Doug Stevenson


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")
like image 31
AndyK Avatar answered Oct 12 '22 23:10

AndyK