I have been trying to figure out a way to query a list of documents where I have a range filter on one field and order by another field which of course isn't possible, see my other question: Order by timestamp with range filter on different field Swift Firestore
But is it possible to save documents with the timestamp as id and then it would sort by default? Or maybe hardcode an ID, then retrieve the last created document id and increase id by one for the next post to be uploaded?
This shows how the documents is ordered in the collection
Any ideas how to store documents so they are ordered by created at in the collection?
It's not well documented but you can do
.order(by: '__name__')
.Firebase sort of talks about it here:
https://github.com/FirebaseExtended/polymerfire/issues/306
If I correctly understood your need, by doing the following you should get the correct order:
For each document, add a specific field of type number, called for example
sortNbr
and assign as value a timestamp you calculate (e.g. the epoch time, see Get Unix Epoch Time in Swift)Then build a query sorted on this field value, like:
See the doc here: https://firebase.google.com/docs/firestore/query-data/order-limit-data
The order of the documents shown in the Firebase console is irrelevant to the functioning of your code that uses Firestore. The console is just for browsing data, and that sorting scheme makes it relatively intuitive to find a document you might be looking for, if you know its ID. You can't change this sort order in the console.
Your code is obviously going to have other requirements, and those requirements should be coded into your queries, without regarding any sort order you see in the dashboard.
Yes, you can do this.
See the docs here: https://firebase.google.com/docs/firestore/query-data/order-limit-data
So if you find a way to use a timestamp or other primary key value where the ascending lexicographical ordering is what you want, you can filter by any fields and still have the results sorted by the primary key, ascending.
Be careful to zero-pad your numbers to the maximum precision if using a numeric key like seconds since epoch or an integer sequence. 10 is lexicographical less than 2, but 10 is greater than 02.
Using ISO formatted
YYYY-mm-ddTHH:MM:SS
date-time strings would work, because they sort naturally in ascending order.