How to get a list of document IDs in a collection Cloud Firestore?

I have a collection of documents with generated identifiers. The question is: is it possible to get a list of identifiers without querying all documents data? Is it better to store these keys in a separate collection?


The answer depends on which API you're trying to use.

For mobile/web SDKs there is no way to do what you're asking for since these clients do not support projections of any kind.

For server SDKs you can do an empty projection, i.e.

db.collection('foo').select()

In this case the server will send you the documents that match, but will omit all fields from the query result.

For the REST API you can do the equivalent with a runQuery that includes a field mask of '__name__', like so:

curl -vsH 'Content-Type: application/json' \
  --data '{
    "parent": "projects/my-project/databases/(default)",
    "structuredQuery":{
      "from": [{"collectionId": "my-collection"}],
      "select": {
        "fields": [{"fieldPath":"__name__"}]
      }
    }
  }' \
  'https://firestore.googleapis.com/v1beta1/projects/my-project/databases/(default)/documents:runQuery'

Substitute my-project and my-collection as appropriate. Note that the "collectionId" in the "from" is only the right most name component. If you want keys in a subcollection the REST API wants the parent document name in the "parent" field.


On node.js runtime you can get the list of document IDs like this

const documentReferences = await admin.firestore()
        .collection('someCollection')
        .listDocuments()

const documentIds = documentReferences.map(it => it.id)