Order by document id firestore?

让人想犯罪 __ 提交于 2020-01-10 05:24:19

问题


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?


回答1:


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.




回答2:


It's not well documented but you can do .order(by: '__id__'), and in JavaScript there is a more idiomatic solution using an internal variable:

.orderBy(firebase.firestore.FieldPath.documentId())

Firebase sort of talks about it here:

https://github.com/FirebaseExtended/polymerfire/issues/306




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/50010771/order-by-document-id-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!