Firestore Order by Time But Sort by Id

Firestore order by time but sort by ID

The order of the documents shown in the Firebase console is mostly 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. If you want time-based ordering of your documents, you'll have to store some sort of timestamp field in the document, and use that for ordering. I don't recommend using the timestamp as the ID of a document, as that could cause problems for you in the future.

Order Firestore data by TimeStamp in Ascending order

You cannot use a String (timeStamp) when querying your database instead of a Date (date) and expect to behave as it was a date. So to solve this, please change the following line of code:

firestoreDb.collection("ideas")
.orderBy("timeStamp", Query.Direction.ASCENDING)

to

firestoreDb.collection("ideas")
.orderBy("date", Query.Direction.ASCENDING)

To make it work, this kind of query requires an index. To create one, please check my answer from the following post:

  • Firestore whereEqualTo, orderBy and limit(1) not working

How to retrieve documents in firestore order with timestamp with React

Firestore can only order/filter data on values that it has indexes for. Indexes are only created for fields in your document (and the document ID), not for implicit metadata such as the timestamp it keeps internally.

There is no way to order Firestore results based on the internal timestamp. If you want to be able to order documents on a timestamp, you'll have to store that timestamp as a field in the document, and then pass that field name to orderBy.

Firestore - How to fetch 5 latest document with order by time asc

This isn't possible with a single query without adding in some client code to sort the results a second time.

You will want a descending sort with limit 5.

    firebase.firestore().collection(collection).doc(doc).collection(collection)
.orderBy("time", "desc").limit(5)

This should get you the 5 newest documents by time. But then you will have to re-sort the documents by ascending time in thh client if you want to iterate or display them in ascending order.

How can I limit and sort on document ID in firestore?

A few points. It is ALWAYS a good practice to use random, well distributed documentId's in firestore for scale and efficiency. Related to that, there is effectively NO WAY to query by documentId - and in the few circumstances you can use it (especially for a range, which is possible but VERY tricky, as it requires inequalities, and you can only do inequalities on one field). IF there's a reason to search on an ID, yes it is PERFECTLY appropriate to store in the document as well - in fact, my wrapper library always does this.

the correct notation, btw, would be FieldPath.documentId() (method, not constant) - alternatively, __name__ - but I believe this only works in Queries. The reason it requested a new index is without the () it assumed you had a field named FieldPath with a subfield named documentid.

Further: FieldPath.documentId() does NOT generate the documentId at the server - it generates the FULL PATH to the document - see Firestore collection group query on documentId for a more complete explanation.

So net:

=> documentId's should be as random as possible within a collection; it's generally best to let Firestore generate them for you.

=> a valid exception is when you have ONE AND ONLY ONE sub-document under another - for example, every "user" document might have one and only one "forms of Id" document as a subcollection. It is valid to use the SAME ID as the parent document in this exceptional case.

=> anything you want to query should be a FIELD in a document,and generally simple fields.

=> WORD TO THE WISE: Firestore "arrays" are ABSOLUTELY NOT ARRAYS. They are ORDERED LISTS, generally in the order they were added to the array. The SDK presents them to the CLIENT as arrays, but Firestore it self does not STORE them as ACTUAL ARRAYS - THE NUMBER YOU SEE IN THE CONSOLE is the order, not an index. matching elements in an array (arrayContains, e.g.) requires matching the WHOLE element - if you store an ordered list of objects, you CANNOT query the "array" on sub-elements.

Document's IDs and order by in a query throws an error (Firestore)

Firestore can't execute this query because the "in" filter uses document ID (internally known as "__name__"), which is different than your sort order.

The easiest workaround is to simply sort the documents in your app code. Since an "in" query can only return 10 documents maximum, this should pose no real problems at all on modern hardware.

Firestore search and order by document id or by document field, which is a better way?

A: I set the food name as the document id (assume they are all unique) and each of them has a field called "price", and another architecture B is to make the document a random id and set the food name into the field "name"

In my opinion, B is the option you can go ahead with. This means that this approach is more likely to be used if you want your app to massively scale. Please also see Dan McGrath's answer from the following post:

  • Limitations of using sequential IDs in Cloud Firestore

The second question is for document ordering (or maybe for filtering), A: I set the document id as event timestamp string, and each of them has a field called "event", and another architecture B is to make the document a random id and make the time data into the field "time"

Again, B is the option you can go ahead with. To order the results of a query, you can simply pass the direction as the second argument to the orderBy() method:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference eventsRef = rootRef.collection("Events");
Query queryEventsByTime = eventsRef.orderBy("time", Query.Direction.ASCENDING);

Or Query.Direction.DESCENDING, according to your needs. But be aware that the time property should be of type Date and not of type String, as I see in your schema. To be able to save the date in Firestore, please see my answer from the following post:

  • ServerTimestamp is always null on Firebase Firestore


Related Topics



Leave a reply



Submit