首页 > 解决方案 > FireStore - 在数组中搜索值

问题描述

好的,所以我一直在网上搜索,找不到我的问题的解决方案。我使用了以下查询,但仍然没有运气:

        .whereField("Features.tagName", arrayContains: tagName)
        .whereField("Features", arrayContains: "tagName: \(tagName)")
        .whereField("Features", arrayContains: "tagName: \(tagName)")
        .whereField("Features", arrayContainsAny: [tagName])
        .whereField("Features", in: [tagName])
        .whereField("Features.tagName", arrayContainsAny: [tagName])

我想我会添加这些以显示我是否走在正确的轨道上,并希望避免任何混淆或推荐任何这些查询作为解决方案的事件。

我指向正确的集合,因为我声明了一个全局常量,我可以调用它并用于其他查询/方法。

我的数据库结构如下:

Post - 
 PostID -
   username
   date
   features[]

但是,必须注意我的 features 数组的结构如下:

features: [
[0] tagName: "Blue",
[1] tagName: "Yellow"
]

我似乎无法返回任何东西。我只查询一个标签。我有一种强烈的感觉,这是因为tagName。但我已经使用插值或尝试过,但仍然没有运气。

有人知道我哪里出错了吗?

标签: swiftfirebasegoogle-cloud-firestore

解决方案


正如您在评论中提到的,推荐的方法是删除,tagName因为所有数组元素都将具有键tagName并将结构保留为:

features: [
  "Blue",
  "Yellow"
]

然后就可以查询了:

db.collection("Post")
  .whereField("features", arrayContains: "Blue")

但是,如果无法更改结构,您可以将其查询为:

db.collection("Post")
  .whereField("features.tagName", isEqualTo: "Blue")

推荐阅读