18

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?

Markus Marvell
  • 1,826
  • 1
  • 18
  • 26

2 Answers2

40

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.

Michael Lehenbauer
  • 16,031
  • 1
  • 55
  • 59
8

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)
Safwan
  • 3,014
  • 1
  • 25
  • 32
sillo01
  • 464
  • 5
  • 12
  • Solved my problem. This usage seems not documented elsewhere. – Josan Sep 26 '20 at 03:33
  • 2
    Note: the `in` filter only accepts a maximum of 10 entries before throwing an error, so be ready if you have this in production code... – bsplosion Nov 05 '21 at 01:06