首页 > 解决方案 > Firebase Firestore 中的嵌套查询

问题描述

我有一个这样的 Firestore 数据库结构:(文章是一个集合,里面的一切都是数组)

Articles:
[
    {
        "id": 1,
        "reports": [
            {
                "locations": [
                    {
                        "location": "Sydney",
                        "country": "Australia"
                    },
                    {
                        "location": "Perth",
                        "country": "Australia"
                    }
                ],
            },
            {
                "locations": [
                    {
                        "location": "King County, Washington",
                        "country": "USA"
                    }
                ],
            }
        ]
    },
    {
        "id": 2,
        "reports": [
            {
                "locations": [
                    {
                        "location": "Brisbane",
                        "country": "Australia"
                    }
                ]
            }
        ]
    }
]

我想创建一个查询以返回所有提及特定国家的文章。我最好重组我的数据库吗?

标签: firebasegoogle-cloud-firestore

解决方案


虽然 Firestore 的array-contains查询可以让您接近这一点,但您不能在当前数据模型中使用它们,因为您正在嵌套数组。

为了允许用例,您至少需要将其中一个数组取消嵌套到每篇文章的子集合中,因此:

Articles (collection)
  $article
    reports (collection)
      $report (document with a locations array)

此时您可以使用集合组查询来搜索所有reports集合,然后array-contains找到相关的报告文档:

var ref = firebase.firestore().collectionGroup("reports");
ref.where("locations", "array-contains", { location: "Sydney", country: "Australia" })

别介意下面的答案,假设你只有一层数组......

据我所知,使用运算符应该可以进行这种类型的查询array-contains。请记住,您需要指定整个数组项。

所以像:

collectionRef.where("reports.locations", "array-contains", 
                        { location: "Sydney", country: "Australia" })


推荐阅读