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

Android端Firestore查询:筛选orders集合指定状态的文档

如何在Firestore中查询指定状态的订单文档

很简单,我们可以利用Firestore的in查询操作符来匹配多个指定的status值,刚好满足你要筛选Pending、Cooking、Cooked这三种状态订单的需求。下面分不同平台的SDK给你提供具体实现:

Web SDK(模块化 v9)

import { collection, query, where, inArray, getDocs } from "firebase/firestore";

// 假设db是你的Firestore实例
const ordersRef = collection(db, "orders");
// 构建查询:筛选status在指定数组中的文档
const statusQuery = query(ordersRef, where("status", "in", ["Pending", "Cooking", "Cooked"]));

// 执行查询并处理结果
try {
  const querySnapshot = await getDocs(statusQuery);
  querySnapshot.forEach((doc) => {
    console.log(`订单ID: ${doc.id}, 详情:`, doc.data());
  });
} catch (error) {
  console.error("查询订单失败:", error);
}

Web SDK(命名空间 v8)

// 假设db是你的Firestore实例
const ordersRef = db.collection("orders");
const statusQuery = ordersRef.where("status", "in", ["Pending", "Cooking", "Cooked"]);

// 执行查询
statusQuery.get().then((querySnapshot) => {
  querySnapshot.forEach((doc) => {
    console.log(`订单ID: ${doc.id}, 详情:`, doc.data());
  });
}).catch((error) => {
  console.error("查询订单失败:", error);
});

Android(Kotlin)

import com.google.firebase.firestore.FirebaseFirestore

val db = FirebaseFirestore.getInstance()
val ordersRef = db.collection("orders")
val statusQuery = ordersRef.whereIn("status", listOf("Pending", "Cooking", "Cooked"))

statusQuery.get()
    .addOnSuccessListener { querySnapshot ->
        for (document in querySnapshot) {
            println("订单ID: ${document.id}, 详情: ${document.data}")
        }
    }
    .addOnFailureListener { exception ->
        println("查询订单失败: ${exception.message}")
    }

iOS(Swift)

import FirebaseFirestore

let db = Firestore.firestore()
let ordersRef = db.collection("orders")
let statusQuery = ordersRef.whereField("status", in: ["Pending", "Cooking", "Cooked"])

statusQuery.getDocuments { (querySnapshot, error) in
    if let error = error {
        print("查询订单失败: \(error.localizedDescription)")
        return
    }
    guard let documents = querySnapshot?.documents else {
        print("没有找到匹配的订单")
        return
    }
    for document in documents {
        print("订单ID: \(document.documentID), 详情: \(document.data())")
    }
}

小提示

Firestore的in操作符最多支持匹配10个值,你的场景只有3个状态,完全符合限制。如果后续需要扩展状态,只要不超过10个都可以直接在数组里添加。

内容的提问来源于stack exchange,提问作者Zana Mustafa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:18:52