title: How can I limit and sort on document ID in firestore?
body: <p>I have a collection where the documents are uniquely identified by a date, and I want to get the n most recent documents. My first thought was to use the date as a document ID, and then my query would sort by ID in descending order. Something like <code>.orderBy(FieldPath.documentId, descending: true).limit(n)</code>. This does not work, because it requires an index, which can't be created because <code>__name__ only indexes are not supported</code>.</p>
  <p>My next attempt was to use <code>.limitToLast(n)</code> with the default sort, which is documented <a href="https://firebase.google.com/docs/firestore/query-data/get-data" rel="nofollow noreferrer">here</a>.</p>
  <blockquote>
  <p>By default, Cloud Firestore retrieves all documents that satisfy the query in ascending order by document ID</p>
  </blockquote>
  <p>According to that snippet from the docs, <code>.limitToLast(n)</code> should work. However, because I didn't specify a sort, it says I can't limit the results. To fix this, I tried <code>.orderBy(FieldPath.documentId).limitToLast(n)</code>, which should be equivalent. This, for some reason, gives me an error saying I need an index. I can't create it for the same reason I couldn't create the previous one, but I don't think I should need to because they must already have an index like that in order to implement the default ordering.</p>
  <p>Should I just give up and copy the document ID into the document as a field, so I can sort that way? I know it should be easy from an algorithms perspective to do what I'm trying to do, but I haven't been able to figure out how to do it using the API. Am I missing something?</p>
  <p>Edit: I didn't realize this was important, but I'm using the <a href="https://firebase.flutter.dev/docs/firestore/overview/" rel="nofollow noreferrer">flutterfire firestore library</a>.</p>