简体   繁体   English

存取Google Firestore集合的最后N个文件

[英]Access last N documents of Google Firestore collection

I want to access last N documents from google firestore collection. 我想访问Google Firestore集合中的最后N个文档。 The key for documents are timestamp in ISO format. 文档的密钥是ISO格式的时间戳。 The collection first needs to be sorted on timestamp keys and the last N documents updated are to be retrieved. 首先需要按时间戳记密钥对集合进行排序,并且要检索最后更新的N个文档。 This operation has to be realtime and fast. 此操作必须实时且快速。

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

I currently loop through the collection and add the keys to an array and then sort the array and get last N document by those keys as following: 我目前在整个集合中循环,并将键添加到数组中,然后对该数组进行排序并通过这些键获取最后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);
  });

This operation takes a long time if collection size increases. 如果集合大小增加,此操作将花费很长时间。 Is there an optimal way of achieving this (sorting/orderBy-descending collection and fetch last N documents)? 是否有实现此目的的最佳方法(排序/降序收集并获取最后N个文档)?

Thanks 谢谢

也许是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM