Flutter中如何在Firebase Firestore里筛选嵌套Map结构的数据?
在Flutter中筛选Firestore嵌套Map结构的数据

问题描述
各位开发者好:
我有一个技术问题,想请教如何在Flutter中对Firebase Firestore里的嵌套Map结构数据进行筛选。
例如,我要筛选spotProperties字段时,可以通过以下代码实现,且运行正常:
FirebaseFirestore.instance.collection('spots') .where('spotProperties', isGreaterThanOrEqualTo: 'gaps') .snapshots().listen((spots){ mapRecords(spots); });
但当我想要筛选嵌套在spotAddress这个Map里的countryName或cityName字段时,尝试多种方法都未成功,想请教正确的实现方式。
感谢您的回复。
解决方案
要筛选Firestore嵌套Map中的字段,直接使用**点符号(.)**指定完整的字段路径即可,无需额外处理Map结构。
筛选spotAddress.countryName示例
FirebaseFirestore.instance.collection('spots') .where('spotAddress.countryName', isEqualTo: '目标国家名称') .snapshots().listen((spots) { mapRecords(spots); });
筛选spotAddress.cityName示例
FirebaseFirestore.instance.collection('spots') .where('spotAddress.cityName', isGreaterThanOrEqualTo: '目标城市名称') .snapshots().listen((spots) { mapRecords(spots); });
关键注意点
- 字段路径要完全匹配数据结构中的字段名,Firestore对字段名大小写敏感。
- 如果执行复合查询(比如同时筛选多个嵌套字段),需要提前在Firestore控制台创建对应的复合索引,否则查询会抛出索引缺失的错误,控制台会给出自动创建索引的链接。
内容的提问来源于stack exchange,提问作者Dominik Grosser
相关产品推荐
相关产品推荐

