简体   繁体   中英

Select last n records by key in firestore?

How does one select the last n items in a collection in firestore? I'm considering migrating a new project from the real time database to firestore. In the realtime database, I used the below code:

ref.orderByKey().limitToLast(n);

I've reviewed the docs at https://cloud.google.com/firestore/docs/query-data/order-limit-data , and they don't appear to mention how to achieve this in firestore. I suppose I could add a timestamp field to every element of the collection and then order by descending timestamp, but I think there should be an easier way to accomplish this.

In the Firebase Realtime Database there was the concept of a push ID, which was a key that was automatically chronologically ordered. This made ordering nodes chronologically in a query as easy as you've shown.

In Cloud Firestore there is no built-in metadata for when a document was added, or when it was last updated. If you want to build queried based on such metadata, you will have to set the corresponding properties on the documents yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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