如何使用Android在Cloud Firestore中查询特定文档后的集合?

时间:2018-01-15 18:49:02

标签: java android firebase google-cloud-firestore

我有以下数据库结构:

Firestore-root
    |
    --- lists (collection)
          |
          --- userId1 (document)
          |     |
          |     --- userLists (collection)
          |             |
          |             --- docKey1 (document)
          |             |     |
          |             |     --- listName: "ListOne"
          |             |     |
          |             |     --- date: January 15, 2018 at 9:56:24 AM UTC+2
          |             |
          |             --- docKey2 (document)
          |                   |
          |                   --- listName: "ListTwo"
          |                   |
          |                   --- date: January 15, 2018 at 9:58:12 AM UTC+2
          |
          --- userId2 (document)
                |
                --- userLists (collection)
                        |
                        --- docKey1 (document)
                        |     |
                        |     --- listName: "ListOne"
                        |     |
                        |     --- date: January 15, 2018 at 9:56:24 AM UTC+2
                        |
                        --- docKey3 (document)
                              |
                              --- listName: "ListThree"
                              |
                              --- date: January 15, 2018 at 9:59:47 AM UTC+2

使用此数据库结构,我可以简单地查询与特定用户对应的所有列表。但是,如何查询数据库以获取具有特定列表的所有用户?

在这种特殊情况下,如何让所有拥有ListOne列表的用户?结果应为:userId1

我是否需要复制数据或是否有其他方法可以执行此操作?

修改

Firestore-root
    |
    --- allList
           |
           --- listId1 (collection)
                  |
                  --- userId1 (document)
                  |      |
                  |      --- username: "FirstUser"
                  |      |
                  |      --- //other details
                  |
                  --- userId2 (document)
                         |
                         --- username: "SecondUser"
                         |
                         --- //other details

谢谢!

2 个答案:

答案 0 :(得分:2)

无法跨多个子集合扩展查询。查询必须包含在单个集合或子集合中。因此,在猜测您需要复制数据以执行查询时,您才会更正。

答案 1 :(得分:0)

实际上可以做到一招。您可以在docKey1文档中添加 map ,而不是重复数据,正如Todd Kerpelman所说here。你的文件看起来像这样:

userLists (collection)
    |
    --- docKey1 (document)
          |
          --- listName: "ListOne"
          |
          --- date: January 15, 2018 at 9:56:24 AM UTC+2
          |
          --- users
               |
               --- userId1: true
               |
               --- userId2: true

因此,您可以查询该特定文档以获取所有用户ID。因此,通过这种方式,您可以获得所要求的分类。