【问题标题】:Query Firebase Firestore documents by the ID按 ID 查询 Firebase Firestore 文档
【发布时间】:2018-07-06 01:39:11
【问题描述】:

正如我从“Cloud Firestore 数据模型”指南中得到的那样,“每个文档都由一个名称标识。”是否可以通过该文档标识符(即名称或 ID)查询集合?

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

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

【问题讨论】:

    标签: firebase google-cloud-firestore


    【解决方案1】:

    您可以使用特殊标记FieldPath.documentId()按documentId查询,例如:

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

    但请注意,文档 ID 是 字符串,因此这将包括 ID 为“0”或“1”的文档,但不包括“2”,因为“2”>“100”字典序。

    所以如果你想要一个数字查询,你需要将文档 ID 作为数字字段写入文档中,然后对其进行正常查询。

    【讨论】:

    • python 有没有等价物?我没找到!
    • @AníbalRivero 它可能还没有实现。您可能想在github.com/GoogleCloudPlatform/google-cloud-python/issues 上打开一个问题
    • 知道在firebaseConnect 中使用react-redux-firebase 是否可行?
    • @BlunderingPhilosopher 你有没有办法做到这一点?
    • @AníbalRivero 他们添加了 python 等价物,仍在测试中...... google.cloud.firestore_v1.field_path.FieldPath.document_id()
    【解决方案2】:

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

    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)
    

    【讨论】:

    • 解决了我的问题。这种用法似乎没有在其他地方记录。
    • 注意:in 过滤器在抛出错误之前最多只接受 10 个条目,所以如果你在生产代码中有这个,请做好准备......
    猜你喜欢
    • 1970-01-01
    • 2018-12-15
    • 2020-07-22
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多