Firestore搜索数组包含多个值 [英] Firestore search array contains for multiple values

查看:47
本文介绍了Firestore搜索数组包含多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个简单的收藏夹,例如:

If I have a simple collection such as:

Fruits:
  Banana:
   title: "Banana"
   vitamins: ["potassium","B6","C"]
  Apple:
   title: "Apple"
   vitamins: ["A","B6","C"]

如果我要搜索含有维生素B6的水果,则可以执行以下操作:

And if I want to search fruits that contain vitamin B6, I would do the following:

db.collection("Fruits").whereField("vitamins", arrayContains: "A").getDocuments() { (querySnapshot, err)  in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
            }
        }
    }

那将向我展示我集合中所有包含维生素A的水果.但是,我如何能够搜索包含多种维生素(例如维生素B6和C)的水果?我不能简单地搜索["B6","C"],因为它随后会寻找一个数组,而不是独立的字符串.

And that would show me all the Fruits in my collection that contain the vitamin A. However, how would I be able to search fruits that contain multiple vitamins, say vitamins B6 and C? I cannot simply search ["B6","C"] as it would then be looking for an array as opposed to independent strings.

在Cloud Firestore中甚至有可能吗?如果没有,还有其他替代方法吗?

Is this even possible in Cloud Firestore? If not is there any alternative way to do this?

推荐答案

通过在查询中链接条件来寻找匹配多个条件的文档将很诱人:

It would be tempting to to look for documents that match multiple conditions, by chaining the conditions in the query:

db.collection("Fruits")
    .whereField("vitamins", arrayContains: "B6")
    .whereField("vitamins", arrayContains: "C")

但是有关复合查询的文档建议您不能当前在单个查询中有多个arrayContains条件.

But the documentation on compound queries suggests that you cannot currently have multiple arrayContains conditions in a single query.

因此,今天拥有的东西是不可能的.考虑使用映射结构而不是数组:

So, it is not possible with what you have today. Consider instead using a map structure instead of an array:

Fruits:
  Banana:
   title: "Banana"
   vitamins: {
     "potassium": true,
     "B6": true,
     "C": true
   }

然后您可以像这样查询:

Then you could query like this:

db.collection("Fruits")
    .whereField("vitamins.B6", isEqualTo: true)
    .whereField("vitamins.C", isEqualTo: true)

这篇关于Firestore搜索数组包含多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆