0
0
Firebasecloud~5 mins

Array-contains queries in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to find documents in a database where a list includes a specific item. Array-contains queries let you search for documents that have a certain value inside an array field.
When you want to find users who have a specific skill listed in their profile.
When you need to get all orders that include a particular product ID in their items array.
When you want to filter posts that have a certain tag in their tags array.
When you want to check if a chat message includes a specific emoji in its reactions array.
When you want to find events that include a certain participant in their attendees list.
Commands
This command queries the 'users' collection to find all documents where the 'skills' array contains the value 'javascript'.
Terminal
firebase firestore:query --collection=users --where="skills array-contains 'javascript'"
Expected OutputExpected
Document ID: user123 name: Alice skills: ["javascript", "python", "html"] Document ID: user456 name: Bob skills: ["java", "javascript", "css"]
--collection - Specifies which collection to query.
--where - Defines the condition for filtering documents.
This command finds all orders where the 'items' array includes the product ID 'product789'.
Terminal
firebase firestore:query --collection=orders --where="items array-contains 'product789'"
Expected OutputExpected
Document ID: order001 customer: John items: ["product123", "product789"] Document ID: order002 customer: Jane items: ["product789", "product456"]
--collection - Specifies which collection to query.
--where - Defines the condition for filtering documents.
Key Concept

If you remember nothing else from this pattern, remember: array-contains queries let you find documents where a specific value exists inside an array field.

Common Mistakes
Using '==' instead of 'array-contains' to search inside arrays.
The '==' operator checks for exact matches, not values inside arrays, so it won't find documents where the value is inside an array.
Use 'array-contains' in the where clause to search for a value inside an array field.
Trying to use 'array-contains' on fields that are not arrays.
The query will fail or return no results because the field is not an array type.
Ensure the field you query with 'array-contains' is actually an array in your documents.
Summary
Use 'array-contains' in Firestore queries to find documents where an array field includes a specific value.
Run queries with the --where flag specifying 'array-contains' to filter documents by array contents.
Always check that the field you query is an array to avoid errors or empty results.