U. Watt
U. Watt

Reputation: 724

Sort documents in a collection firestore by document ID

I have a collection where I'm storing different chapters in documents, like chapter 1 in a document, chapter 2 in another document and so on.

I want to store these documents in the descending order. I want Chapter 500 to be displayed first, followed by chapter 499 and so on.

I found a similar question, but that was sorting based on a value present in each document. I want the sorting to be done from the document name itself. (The document names are 'Chapter 1', 'Chapter 2' and so on). Is this possible?

Upvotes: 0

Views: 257

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317392

If your document names are formatted like "Chapter 1" and "Chapter 111", then what you're doing isn't possible. Strings don't sort like numbers. Note the sort order of these two strings:

  1. "Chapter 11"
  2. "Chapter 9"

Note that 11 comes before 9 here, because the character 1 sorts lexicographically before character 9, and it doesn't matter what other numbers come after the 1 in the first string.

I strongly suggesting considering using an actual number field in the document for the sort.

Upvotes: 2

Related Questions