Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Firebase Firestore documents by the ID

As I got from 'Cloud Firestore Data Model' guide "each document is identified by a name." Is it possible to query a collection by that document identifier (which is the name or ID)?

For example, documents in the collection "Things" have IDs: 0, 1, 2 etc.:

enter image description here

Is it possible to query documents which IDs are less than 100?

like image 576
Markus Marvell Avatar asked Jan 26 '18 16:01

Markus Marvell


People also ask

How do I get specific data 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.

What is firestore document ID?

On this page. Inherited Method Summary. public abstract @interface DocumentId implements Annotation. Annotation used to mark a POJO property to be automatically populated with the document's ID when the POJO is created from a Cloud Firestore document (for example, via toObject(Class) ).


2 Answers

You can query by documentId using the special sentinel FieldPath.documentId(), e.g.:

const querySnap = collection.where(firebase.firestore.FieldPath.documentId(), '<', '100').get();

But be aware that document IDs are strings and therefore this will include documents with ID '0' or '1', but not '2' since '2' > '100' lexicographically.

So if you want a numeric query, you'll need to write the document ID as a numeric field in the document and then do a normal query on it.

like image 131
Michael Lehenbauer Avatar answered Oct 20 '22 20:10

Michael Lehenbauer


In python, you should use full documents names

from google.cloud import firestore
from google.cloud.firestore_v1.field_path import FieldPath

db = firestore.Client()
colRef = db.collection(u'docs')
filter = [db.document(u'docs/doc1'), db.collection(u'docs/doc3')]
query = colRef.where(FieldPath.document_id(), u'in', filter)
like image 20
sillo01 Avatar answered Oct 20 '22 20:10

sillo01