Firestore Query Subcollection

Created At: 2023-02-14 02:33:39 Updated At: 2023-02-14 17:59:02

Firestore subcollection query is a step by step process from collection to documents  ansd then subcollection. So it's like connecting collection->documents->subcollection

    var result = await FirebaseFirestore
        .instance
        .collection("message")
        .doc(doc_id)
        .collection("msglist")
        .get();

Here,

  1. message is a collection
  2. doc takes document id
  3. msglist is a subcollection

At the end you add get() function to get or retreive all the documents inside the subcollection.

Now we can easily add condition to the above collection. Here we will add a timestamp query based on condition. For query you must call where() function with your collection.

  var result = await FirebaseFirestore
        .instance
        .collection("message")
        .doc(doc_id)
        .collection("msglist")
        .where("addtime", isLessThan: Timestamp.now())
        .get();

It will return you all the documents that's added before the current time. Timestamp.now() returns current time.

All the documents based on the query. This is actually called get documents by field. The query is same.

Let's change the condition

 var result = await FirebaseFirestore
        .instance
        .collection("message")
        .doc(doc_id)
        .collection("msglist")
        .where("content", isEqualTo: "hello")
        .get();

      print(result.docs);

Here we find content field in our subcollection. We check if the content field matches any string or not.

In the above query, we got a few result since it matches fewer texts or strings.

Comment

Add Reviews