按ID查询Firebase Firestore文档

Mar*_*ell 6 firebase google-cloud-firestore

当我从"Cloud Firestore数据模型"指南中获得"每个文档都由一个名称标识".是否可以通过该文档标识符(名称或ID)查询集合?

例如,集合"Things"中的文档具有ID:0,1,2等:

在此输入图像描述

是否可以查询ID小于100的文档?

Mic*_*uer 19

您可以使用特殊的sentinel通过documentId进行查询FieldPath.documentId(),例如:

const querySnap = collection.where(firebase.firestore.FieldPath.documentId(), '<', '100').get();
Run Code Online (Sandbox Code Playgroud)

但要注意文档ID是字符串,因此这将包括ID为"0"或"1"的文档,但不包括"2",因为"2">"100"按字典顺序排列.

因此,如果您需要数字查询,则需要将文档ID作为数字字段写入文档,然后对其进行常规查询.

  • python有等价物吗?我找不到! (2认同)

sil*_*o01 6

在 python 中,您应该使用完整的文档名称

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

firestore = f.Client()
colRef = firestore.collection(u'docs')
filter = [firestore.document(u'docs/doc1'), firestore.collection(u'docs/doc3')]
query = colRef.where(FieldPath.document_id(), u'in', filter)
Run Code Online (Sandbox Code Playgroud)

  • 注意:“in”过滤器在抛出错误之前最多只接受 10 个条目,因此如果您在生产代码中有此内容,请做好准备... (2认同)