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

Android Firestore数组查询:检测集合中是否存在指定值

Querying Firestore for Documents with Specific Values in an Array

Hey there! Let's sort out how to query your company collection for documents where the card array contains values like 123, 456, or 789. Firestore has specific methods for array-based queries, so let's break this down based on your exact needs:

Case 1: Find documents where the card array contains a single target value

If you want to check for documents that include just one of the values (e.g., 123), use the whereArrayContains method. This matches any document where the specified array field includes the exact value you pass:

CollectionReference ref = db.collection("company");
// Query for documents where "card" array contains 123
Query query = ref.whereArrayContains("card", 123);

Case 2: Find documents where the card array contains any of the target values

If you need to find documents that have any of 123, 456, or 789 in their card array, use whereArrayContainsAny. This method takes a list of values and returns documents where the array includes at least one of them:

CollectionReference ref = db.collection("company");
// Create a list of the values you want to check for
List<Integer> targetCardValues = Arrays.asList(123, 456, 789);
// Query for documents where "card" array has any of the values in the list
Query query = ref.whereArrayContainsAny("card", targetCardValues);

Case 3: Find documents where the card array contains all target values

Firestore doesn't have a built-in method to directly query for arrays that include every value in a list. If this is your requirement, you have two practical options:

  • Client-side filtering: Run the whereArrayContainsAny query first, then filter the results in your app to only keep documents where the card array includes all three values.
  • Restructure your data: Instead of using an array, store the card values as keys in a map (e.g., cardMap: { "123": true, "456": true }). Then you can use multiple whereEqualTo clauses to check for all required values:
    Query query = ref
        .whereEqualTo("cardMap.123", true)
        .whereEqualTo("cardMap.456", true)
        .whereEqualTo("cardMap.789", true);
    

Quick reminder: Make sure the data type of the values you're querying matches what's stored in Firestore (e.g., if your card values are integers, pass integers; if they're strings, pass strings).

内容的提问来源于stack exchange,提问作者Pemba Tamang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:46:36