is there any way to get all unique field value in firestore using a collectionGroup query like a SELECT DISTINCT ?

fetchAvailableZipCode() {
    try {
      _availableZipCodeStream = FirebaseFirestore.instance
          .collectionGroup(PLACES_COLLECTION)
          .orderBy('cityZipCode', descending: true)
          .snapshots()
          .listen((event) {
        List<String> currentAvailableZipCode = [];
        event.docs.map((e) {
          if (!currentAvailableZipCode
              .contains(e.get('cityZipCode').toString()))
            currentAvailableZipCode.add(e.get('cityZipCode').toString());
        }).toList();
        _availableZipCode.value = currentAvailableZipCode;
        print(_availableZipCode.toString());
        print(_availableZipCode.length.toString() + ' available');
      });
    } catch (e) {
      Get.snackbar('app_error'.tr, 'app_error_description'.tr);
    }
  }


Solution 1: Frank van Puffelen

Firestore does not have an operator like select distinct, nor any other data aggregation operations. It returns the data exactly as it is stored.

That means that if you want to get the distinct values of a certain field, you have two options:

  • Retrieve all documents from the database and determine the distinct values in your application code.
  • Use the distinct values in an additional collection as the document key, so that you can then read all documents from that collection when you need the distinct values.

The latter is idiomatic in Firestore and many other NoSQL databases: you end up changing your data model and duplicating data to fit specific use-cases of your app.