Ofc,我知道我们从一个集合中检索一大堆文档的基本方法,如下所示:
stream: Firestore.instance
.collection("collection_name")
.orderBy("date", descending: true) // new entries first
.snapshots(),
builder: (context, snapshot) { ....
当我显示一大堆数据时,这很好。
但是我有需要对最后添加的数字进行一些计算的情况,这意味着我只需要获取 1 个文档,所以我所做的是按日期对数据进行排序并按 1 限制,然后对这个文档进行查询,例如这
List<DocumentSnapshot> list;
QuerySnapshot querySnapshots;
if (await AuthHelper.checkIfUserIsLoggedIn()) {
String userId = await AuthHelper.getUserID();
querySnapshots = await Firestore.instance
.collection("collection_name")
.orderBy("date", descending: true) // new entries first, date is one the entries btw
.limit(1)
.getDocuments(); // Get Documents not as a stream
list = querySnapshots.documents; // Make snapshots into a list
return (list ?? null);
} else {
return null;
}
但这是最好的方法吗?进行此查询时,我不是获取了整套文档并丢弃了其余文档吗?这意味着当这个集合增长时,它会变得越来越慢?
有没有更好的方法来检索最后添加的文档?所以我可以将它用作列表/数组/映射而不是流?
谢谢。
当您限制查询时,您只会读取该数量的文档max。它不会读取整个集合并丢弃额外内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句