Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a firestore query in chronological order on creation

I built a collection and added some documents sequentially (a few seconds apart). firestore generated each doc.id automatically.

In the documentation it says each doc.id key consists of a timestamp part and random part (presumably to ensure there are no key collisions). Edit: I had read this on an unrelated blog post, so I've removed this to avoid confusion.

Since If the key were to contain some (hidden) chronology, is it possible to do a firestore query based on this key and thus get the result set in ascending or descending chronological order?

like image 976
Andy Fusniak Avatar asked May 31 '18 09:05

Andy Fusniak


People also ask

How do I get sorted data from firestore?

By default, a query retrieves all documents that satisfy the query in ascending order by document ID. You can specify the sort order for your data using orderBy() , and you can limit the number of documents retrieved using limit() . Note: An orderBy() clause also filters for existence of the given field.

How do I query a collection in firestore?

To start querying a collection, you need to provide the hooks with a CollectionReference or Query reference created directly from the firebase/firestore library. The reference can be a simple collection pointer or a fully constrained query using the querying functionality provided by the Firestore SDK.

How does firestore query work?

Cloud Firestore is a database for web and mobile applications, often chosen for its flexibility and scalability. Cloud Firestore leverages the technologies of Firebase technologies with the Google Cloud Platform. It performs real-time synchronization of data between client applications using event listeners.


1 Answers

Unfortunately, Cloud Firestore auto-generated IDs do not provide any automatic ordering, and cannot be relied-upon to be chronological. To order your documents chronologically, you should add your own timestamp field to the documents.

From the Firestore add a document documentation:

Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents.

like image 189
Grimthorr Avatar answered Sep 29 '22 15:09

Grimthorr