【问题标题】:Firestore - Nested queryFirestore - 嵌套查询
【发布时间】:2019-07-18 08:22:07
【问题描述】:

我真的是 firebase 新手,老实说,我发现查询很难写。我正在使用firebase_admin 在 python 中编写脚本,我希望查询/答案使用 python 代码,但使用任何其他编程语言都可以。

这是我的一份文件,一份文件包含photosset

photos: {
    id1: true
    id2: true
}

我想在照片对象中检索他们有 id1 的所有项目,对此的查询是什么?

【问题讨论】:

    标签: python firebase google-cloud-firestore firebase-admin


    【解决方案1】:

    正如Firebase documentation on simple queries 所示:

    # Create a reference to the photos collection
    ref = db.collection('documents')
    
    # Create a query against the collection
    query_ref = ref.where(u'photos.id1', u'==', True)
    

    有关. 表示法,请参阅fields in nested objects 上的文档。

    请注意,您可能希望更改数据模型以使用数组来存储此数据,例如arrays can now be used to model mathematical sets。在您的文档中使用这样的数组:

    user: ['id1', 'id2']
    

    然后您可以使用以下内容进行过滤:

    photos_ref = db.collection('documents')
    
    query = photos_ref.where(u'photos', u'array_contains', u'id1')
    

    要向这个行为类似的数组添加/删除项目,请参阅updating elements in an array 上的文档。

    【讨论】:

    【解决方案2】:

    基于 Frank van Puffelen 的解决方案,我还能够使用点符号来实现嵌套效果。查询分配中包含当前用户 ID 的对象。

    objectModel: {
          objectName: 'foo',
          otherField: 'bar',
          assignment: {
              installerIds: ['1', '2', '3'],
              otherfields: 'foobar'
          },
    }
    

    我可以这样查询

    p = { 字段:'assignment.installerIds',运算符:'array-contains',值:this.currentInstallerId} query = query.where(p.field, p.operator, p.value);

    或者像弗兰克展示的更一般的格式:

    query_ref = ref.where('assignment.installerIds', 'array-contains', '2');
    

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 2022-12-01
      • 2019-07-06
      • 2018-05-18
      • 1970-01-01
      相关资源
      最近更新 更多