【问题标题】:How to retrieve 1 document from firebase/firestore collection based on date in dart/flutter?如何根据 dart/flutter 中的日期从 firebase/firestore 集合中检索 1 个文档?
【发布时间】:2019-10-12 09:23:03
【问题描述】:

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

但这是最好的方法吗?进行此查询时,我不是得到了整套文档并丢弃了其余文档吗?这意味着当这个集合增长时,它会变得越来越慢?

有没有更好的方法来检索最后添加的文档?所以我可以将它用作列表/数组/映射而不是流?

谢谢。

【问题讨论】:

    标签: firebase collections flutter dart google-cloud-firestore


    【解决方案1】:

    当您限制查询时,您只会阅读该数量的文档最大。它不会读取整个集合并丢弃额外内容。

    【讨论】:

    • 嗯,但我是先按日期排序的,所以这不意味着,它正在对所有这些进行排序吗?
    • 不,排序发生在服务器上,它使用索引来确定实际读取哪些文档。 Firestore 不允许您执行任何无法扩展的查询。
    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 2020-06-02
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多