Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get documents descending by DocumentID?

I am encountering the issue encountered in this question. Because the other question (and answer) is missing the point of solving the problem, I am writing a new question.

orderBy(FieldPath.documentId(), 'desc')

The above query will fail with the following error message:

The query requires an index. You can create it here: ...

As described in the other question, it is impossible to create that index because of the following error message:

__name__ only indexes are not supported

Because the opposite query works fine:

orderBy(FieldPath.documentId(), 'asc')

I am wondering why the descending query does not work. To me that does not really make a lot of sense, especially because this should be a very common use case.

It would be awesome if there is a solution to the above problem, i.e. if there is a way to create an index that makes 'desc' work. However, I expect that it just is not a possibility and will therefore phrase a broader problem.

How do I really get my documents in descending order by the Document ID?

I could obviously do the 'asc' query and then reverse my retrieved list.
But this does not work because I need to limit() the query. I cannot just pay for all the documents in a collection just to get a descending order.
This way I would get billed for all document reads in the collection even if I just wanted to get a single one (the last one). Here is a great article discussing potential consequences of this because it does not scale.

Do I really need to create a field called id, which contains the exact same documentID, just to create an index on it and then be able to query descendingly?
A potential collection could look like this:

"q":
 - id: "q"
"u":
 - id: "u"
"i":
 - id: "i"
"t":
 - id: "t"
"e":
 - id: "e"
"d":
 - id: "d"
"u":
 - id: "u"
"m":
 - id: "m"
"b":
 - id: "b"
like image 536
creativecreatorormaybenot Avatar asked Aug 31 '18 16:08

creativecreatorormaybenot


People also ask

How do I reorder documents in firebase?

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 to delete document in Firestore react native?

You can delete documents within Cloud Firestore using the delete method on a DocumentReference : import firestore from '@react-native-firebase/firestore'; firestore() . collection('Users') . doc('ABC') .


1 Answers

Currently it's not possible to perform a descending query based on document ID. Your alternative is to put the document ID in a field of the document, and use that for ordering.

Feel free to also file a feature request for this, but it's not likely to happen in the near term.

like image 123
Doug Stevenson Avatar answered Oct 02 '22 16:10

Doug Stevenson