Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 330
elliezen Avatar asked Nov 01 '17 19:11

elliezen


People also ask

How do I get a list of documents from firestore?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.


2 Answers

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.

like image 150
Gil Gilbert Avatar answered Oct 01 '22 06:10

Gil Gilbert


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) 
like image 38
tomrozb Avatar answered Oct 01 '22 06:10

tomrozb