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

查看:20
本文介绍了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
   }

然后你可以这样查询:

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

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

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