Order by document id firestore?

2019-07-22 14:21发布

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

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?

4条回答
一纸荒年 Trace。
2楼-- · 2019-07-22 14:46

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

查看更多
Bombasti
3楼-- · 2019-07-22 14:50

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:

let docRef = db.collection("xxxx")
docRef.order(by: "sortNbr")

See the doc here: https://firebase.google.com/docs/firestore/query-data/order-limit-data

查看更多
Explosion°爆炸
4楼-- · 2019-07-22 14:55

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.

查看更多
Evening l夕情丶
5楼-- · 2019-07-22 15:08

Yes, you can do this.

By default, a query retrieves all documents that satisfy the query in ascending order by document ID.

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.

查看更多
登录 后发表回答