0

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

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
pawchi
  • 77
  • 7
  • You can query on [`FieldPath.documentId()`](https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/FieldPath#documentId()) as shown here: https://stackoverflow.com/a/52252264 – Frank van Puffelen Feb 07 '21 at 19:42
  • @FrankvanPuffelen That won't help - the data to be filtered is in field of the document. The problem here is that Firestore doesn't support queries that require the use of field name substrings. The document structure will need to change in order to support this requirement. The field names are too specific to be used for date-level filtering. – Doug Stevenson Feb 07 '21 at 20:17

1 Answers1

1

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • The idea with array works the best for my purpose. Easy finding all time records for user and date. Thanks! – pawchi Feb 08 '21 at 12:21
  • Good to hear. If that works: consider if you really need all the `20210203201512` fields too, as those (by default) each create a separate index, so may end up consuming quite some disk space over time. – Frank van Puffelen Feb 08 '21 at 15:22