Skip to content
Advertisement

Android Cloud Firestore document fields query

How to query all timestamps for a certain date (20210205) and certain user (ala) from Cloud Firestore in the below example? For now, I can download the entire document and filter it on the device. But it’s not effective.

FirebaseFirestore db = FirebaseFirestore.getInstance();
    db.collection("companies").document("softnet").collection("users")
            .document("ala").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            Log.d(TAG, "result: " + task.getResult().getData());
        }
    });

enter image description here

Advertisement

Answer

You can filter for FieldPath.documentId() as shown here to get the ala document in a query. But as you commented yourself, there’s no way to then filter with a wildcard of fields.

The best I can quickly think of is to store an array of dates:

dates: ["20210203", "20210205", "20210207"]

If you use the arrayUnion operator to add values to this array, you’ll never end up with duplicates, and then you can use array-contains to check if the array contains a specific date.

So in total that’d be something like (syntax errors definitely possible):

CollectionRefefence users = db.collection("companies").document("softnet").collection("users");
users
  .whereEqualTo(FieldPath.documentId(), "ala")
  .whereArrayContains("date", "20210207");

Honestly though, you’ll have to consider if the complexity is worth it, as it’s probably simpler to just read the single document that this query returns, and check for the date field in application code.

Advertisement