You need to enable JavaScript to run this app. Firebase如何查询数组字段包含指定值的文档(JavaScript实现)
优惠活动
大模型
产品
解决方案
定价
更多

Firebase如何查询数组字段包含指定值的文档(JavaScript实现)

Firebase Firestore 数组字段包含查询实现方案(JavaScript环境)

Firestore 提供了专用的array-contains查询运算符,专门用于筛选数组字段包含目标值的文档,针对你给出的Cats集合结构,不同版本的Firebase JS SDK写法如下:

Firebase JS SDK v9+ 模块化写法(当前官方推荐)

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

// 已完成Firebase初始化的前提下获取db实例
const db = getFirestore();

// 构造查询条件
const catsQuery = query(
  collection(db, "Cats"),
  where("colors", "array-contains", "orange")
);

// 执行查询获取结果
const querySnapshot = await getDocs(catsQuery);
const matchedCats = [];
querySnapshot.forEach((doc) => {
  matchedCats.push({
    id: doc.id,
    ...doc.data()
  });
});
// matchedCats即为符合要求的文档数组,包含Meowy、Purro两个文档

Firebase JS SDK v8 旧版命名空间写法(兼容历史项目)

// 已完成Firebase初始化的前提下获取db实例
const db = firebase.firestore();

db.collection("Cats")
  .where("colors", "array-contains", "orange")
  .get()
  .then((querySnapshot) => {
    const matchedCats = [];
    querySnapshot.forEach((doc) => {
      matchedCats.push({
        id: doc.id,
        ...doc.data()
      });
    });
    // 在这里处理查询结果
  });

注意:该查询使用Firestore默认自动创建的单字段索引,无需额外手动配置索引即可直接运行。

内容的提问来源于stack exchange,提问作者big papa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 03:24:03