You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore数组嵌套对象条件查询的Swift正确实现方法

Firestore数组嵌套对象查询问题

数据库结构

forms
  -- status: "IN_PROGRESS"
  -- approvalBy: (array)
     [0]
     -- status: "current"
     -- uid: "1111"
     -- order: 10
     [1]
     -- status: "waiting"
     -- uid: "1111"
     -- order: 20

查询需求

  • 文档的status字段等于"IN_PROGRESS"
  • approvalBy数组中存在一个元素,同时满足status: "current"和uid: "1111"

错误尝试分析

你之前的几种写法都无法满足需求,原因如下:

  1. 直接用isEqualTo匹配数组:只有当approvalBy数组和你传入的数组完全一致时才会匹配,显然不符合实际场景。
  2. 错误使用array-contains-any:array-contains-any需要传入包含多个匹配项的数组,而非单个对象,且此处不需要"any"逻辑。
  3. 拆分字段路径查询:approvalBy.status和approvalBy.uid的组合查询会匹配数组中任意元素满足status=current、任意元素满足uid=1111的文档,但这两个条件可能来自数组中的不同元素,无法保证是同一个元素同时满足两个要求。

正确查询方式

使用arrayContains匹配包含指定键值对的对象(Firestore会匹配数组中存在至少一个对象包含这些键值对,无论该对象是否有其他字段),结合status的条件即可:

let db = Firestore.firestore()
let collectionName = "forms"

// 构建查询
let query = db.collection(collectionName)
    .whereField("status", isEqualTo: "IN_PROGRESS")
    .whereField("approvalBy", arrayContains: [
        "status": "current",
        "uid": "1111"
    ])

// 执行查询
query.getDocuments { snapshot, error in
    if let error = error {
        print("查询出错:\(error.localizedDescription)")
        return
    }
    
    guard let docs = snapshot?.documents else {
        print("未找到匹配文档")
        return
    }
    
    for document in docs {
        print("匹配文档ID:\(document.documentID),数据:\(document.data())")
    }
}

这种写法会精准匹配同时满足两个条件的文档:status为IN_PROGRESS,且approvalBy数组中存在同一个元素同时拥有status: "current"和uid: "1111"。

内容的提问来源于stack exchange,提问作者Joe Huang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:27:27