【问题标题】:how to remove elements from array in firestore with a where clause in python如何使用python中的where子句从firestore中的数组中删除元素
【发布时间】:2021-02-20 17:50:11
【问题描述】:

我的 Firestore 中有一个样本集合

我在一个文档中有两个数组。如果monthName 是一月,我想从两个数组中删除整个数组字典。

期望的输出

我试过了

doc_ref = db.collection('calender').where('monthName', 'array_contains', 'January').arrayremove()

但是我遇到了一个错误

AttributeError: 'Query' object has no attribute 'arrayRemove'

我参考了文档,但我无法理解这个问题。所以,在这里寻求帮助。

【问题讨论】:

    标签: python arrays firebase google-cloud-firestore


    【解决方案1】:

    Firestore 没有更新查询的概念,您可以在其中向数据库发送条件和操作。相反,您必须:

    1. 执行查询以获取所有符合您条件的文档。
    2. 循环遍历 Python 代码中的文档。
    3. 然后使用更新调用从每个文档中删除该数组。

    此外,arrayRemove 只能在您知道要从数组中删除的确切、完整项目的情况下使用,您必须:

    1. 加载文档(同上)。
    2. 获取数组,然后删除项目。
    3. 将剩余的整个数组写回数据库。

    【讨论】:

    • 那么没有办法像上面提到的那样从数组中更新/删除?
    • 这确实是不可能的。我在答案中添加了更多信息。
    • 你能给我一份你的解释吗?这很容易理解
    • 我建议看看这些,因为有关如何从数组中删除项目的问题会定期弹出:stackoverflow.com/…
    【解决方案2】:

    您可以创建firestore index 以在不知道文档 ID 的情况下查询文档。如果您在字段month1month2calender 上创建索引,您的CollectionGroup 查询将成功运行(伪代码):

    objectToDelete = {id: 1, monthName: "January"}
    
    for month in ["month1", "month2"]:
      matchingDocRefs = db.collection("calender")
                       .where(month, "array-contains", objectToDelete)
                       .get() // Returns a list of matching DocumentReferences
      for documentRef in matchingDocRefs:
          documentRef.update({ month, firestore.ArrayRemove(objectToDelete)})
    

    在 JavaScript 中测试和工作。

    参考:

    P.S.,它的拼写是“calendar”,而不是“calender”

    【讨论】:

      猜你喜欢
      • 2018-04-21
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-07
      相关资源
      最近更新 更多