firebase - 在firestore颤动中选择不同的替代方法
问题描述
有没有办法使用collectionGroup
类似的查询来获取firestore中的所有唯一字段值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 没有像 select distinct 之类的运算符,也没有任何其他数据聚合操作。它完全按照存储的方式返回数据。
这意味着,如果您想获取某个字段的不同值,您有两种选择:
- 从数据库中检索所有文档并确定应用程序代码中的不同值。
- 使用附加集合中的不同值作为文档键,以便您可以在需要不同值时从该集合中读取所有文档。
后者在 Firestore 和许多其他 NoSQL 数据库中是惯用的:您最终会更改数据模型并复制数据以适应应用程序的特定用例。