Android Firestore数组查询:检测集合中是否存在指定值
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
whereArrayContainsAnyquery first, then filter the results in your app to only keep documents where thecardarray 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 multiplewhereEqualToclauses 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

