首页 > 解决方案 > 访问 Google Firestore 集合的最后 N 个文档

问题描述

我想从 google firestore 集合中访问最后 N 个文档。文档的关键是 ISO 格式的时间戳。集合首先需要根据时间戳键进行排序,并且要检索最后更新的 N 个文档。此操作必须是实时且快速的。

events(collection) =>
documents as below:
2019-01-07T08:21:18.600Z => {
  symbolname: '10900CE',
  price: '10825.0',
  timestamp: '2019-01-07T13:51:18Z',
  quantity: '2.0',
  side: 'SELL' }
2019-01-07T08:21:28.614Z => { 
  symbolname: '10800PE',
  price: '10825.0',
  timestamp: '2019-01-07T13:51:28Z',
  quantity: '2.0',
  side: 'BUY' }
2019-01-07T09:45:24.783Z => { side: 'SELL',
  symbolname: '10800PE',
  price: '10805.0',
  timestamp: '2019-01-07T15:15:24Z',
  quantity: '2.0' }

我目前遍历集合并将键添加到数组中,然后对数组进行排序并通过这些键获取最后 N 个文档,如下所示:

var ids = []
db.collection('events').get()
  .then((snapshot) => {
    snapshot.forEach((doc) => {
      ids.push(doc.id)
    });
  })
  .then(()=>{
    //sortIds(ids);
    console.log(JSON.stringify(ids[ids.length-2])) //second last entry 2019-01-07T08:21:28.614Z
  })
  .catch((err) => {
    console.log('Error getting documents', err);
  });

如果集合大小增加,此操作需要很长时间。是否有实现此目的的最佳方法(排序/orderBy-descending 集合并获取最后 N 个文档)?

谢谢

标签: javascriptgoogle-cloud-firestore

解决方案


也许是这样的:

db.collection('events').orderBy("timestamp").limit(n)

推荐阅读