简体   繁体   中英

Alternative to select distinct in firestore flutter

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM