Bird
Raised Fist0
Firebasecloud~15 mins

Array-contains queries in Firebase - Deep Dive

Choose your learning style10 modes available
Overview - Array-contains queries
What is it?
Array-contains queries let you find documents in a database where a specific array field includes a certain value. Instead of searching for exact matches or simple fields, you can check if an array inside a document holds the value you want. This is useful when data is stored as lists inside documents and you want to filter based on those lists.
Why it matters
Without array-contains queries, you would have to fetch many documents and manually check arrays on the client side, which is slow and inefficient. This query type lets the database do the work, saving time and bandwidth. It makes apps faster and more responsive, especially when dealing with complex data like tags, categories, or user lists.
Where it fits
You should understand basic database queries and how documents and collections work in Firebase before learning this. After mastering array-contains queries, you can explore more advanced queries like array-contains-any or compound queries combining multiple conditions.
Mental Model
Core Idea
An array-contains query asks the database: 'Show me all documents where this array field includes this exact value.'
Think of it like...
Imagine a library where each book has a list of genres written inside. An array-contains query is like asking the librarian to find all books that include 'mystery' in their genre list.
Collection
  │
  ├─ Document 1: { tags: ["red", "blue", "green"] }
  ├─ Document 2: { tags: ["yellow", "blue"] }
  └─ Document 3: { tags: ["red", "black"] }

Query: array-contains 'red'
Result: Document 1, Document 3
Build-Up - 6 Steps
1
FoundationUnderstanding basic document structure
🤔
Concept: Learn how documents store data including arrays.
In Firebase, data is stored in documents inside collections. Each document can have fields with simple values like strings or numbers, or complex values like arrays. For example, a document might have a field 'tags' that holds an array of strings like ['red', 'blue', 'green'].
Result
You can see that documents can hold lists of values, not just single values.
Knowing that documents can store arrays is essential before querying inside those arrays.
2
FoundationBasic querying in Firebase
🤔
Concept: Learn how to query documents by field values.
Firebase lets you ask for documents where a field equals a value. For example, you can find all documents where 'status' equals 'active'. This works well for simple fields but not for arrays.
Result
You understand how to filter documents by simple fields.
This sets the stage to see why array-contains queries are needed for arrays.
3
IntermediateUsing array-contains queries
🤔Before reading on: do you think array-contains can find multiple values at once or only one? Commit to your answer.
Concept: Learn how to query documents where an array field includes a specific value.
The array-contains operator lets you find documents where an array field holds a specific value. For example, query where 'tags' array contains 'blue'. This returns all documents with 'blue' in their tags array.
Result
You can filter documents based on whether their array fields include a value.
Understanding this operator lets you efficiently search inside arrays without manual filtering.
4
IntermediateLimitations of array-contains queries
🤔Before reading on: can array-contains find documents with any of multiple values in the array? Commit to yes or no.
Concept: Learn what array-contains cannot do and what alternatives exist.
Array-contains only checks for one value at a time. It cannot find documents where the array contains any of several values. For that, Firebase offers array-contains-any. Also, array-contains cannot check for multiple values simultaneously inside the same array.
Result
You know when array-contains is not enough and when to use other query types.
Knowing limitations prevents wasted effort trying unsupported queries and guides you to the right tool.
5
AdvancedCombining array-contains with other filters
🤔Before reading on: do you think you can combine multiple array-contains queries in one request? Commit to yes or no.
Concept: Learn how to combine array-contains with other query filters and the constraints involved.
You can combine array-contains with other filters like equality or range queries on different fields. However, you cannot combine multiple array-contains filters on the same query. Firebase limits queries to one array-contains clause per query.
Result
You can build complex queries but must respect Firebase's rules on array-contains usage.
Understanding query combination rules helps design efficient and valid queries.
6
ExpertPerformance and indexing considerations
🤔Before reading on: do you think array-contains queries require special indexes or run slower than simple queries? Commit to your answer.
Concept: Learn how array-contains queries work under the hood and their impact on performance and indexing.
Array-contains queries require indexes on the array field to run efficiently. Firebase automatically creates some indexes but complex queries may need manual index creation. Because the database must check array contents, these queries can be slower than simple equality queries if indexes are missing. Proper indexing ensures fast results.
Result
You understand how to optimize array-contains queries for production use.
Knowing indexing needs prevents slow queries and unexpected errors in production.
Under the Hood
When you run an array-contains query, Firebase checks the index for the array field to find documents where the array includes the specified value. Internally, the database stores array elements in a way that allows quick lookup of documents containing each element. This avoids scanning all documents and makes queries efficient.
Why designed this way?
Firebase designed array-contains queries to balance flexibility and performance. Arrays are common in real data, but searching inside them is complex. By indexing array elements individually, Firebase enables fast queries without scanning entire collections. Alternatives like scanning all documents would be too slow for large datasets.
Query: array-contains 'blue'

┌───────────────┐
│ Array Index   │
│ 'red'         │──┐
│ 'blue'        │──┼──> Documents with 'blue'
│ 'green'       │──┘
└───────────────┘

Database uses index to jump directly to matching documents.
Myth Busters - 4 Common Misconceptions
Quick: does array-contains find documents with multiple values in the array at once? Commit yes or no.
Common Belief:Array-contains can find documents where the array contains any of several values at once.
Tap to reveal reality
Reality:Array-contains only checks for one specific value inside the array per query. To find documents with any of multiple values, you must use array-contains-any.
Why it matters:Misusing array-contains for multiple values leads to incorrect query results and wasted effort.
Quick: can you combine two array-contains filters in one query? Commit yes or no.
Common Belief:You can combine multiple array-contains filters in a single query to check for several values.
Tap to reveal reality
Reality:Firebase only allows one array-contains filter per query. Trying to combine multiple causes errors.
Why it matters:Trying to combine multiple array-contains filters causes query failures and confusion.
Quick: does array-contains work on fields that are not arrays? Commit yes or no.
Common Belief:Array-contains can be used on any field, even if it is not an array.
Tap to reveal reality
Reality:Array-contains only works on fields that are arrays. Using it on non-array fields results in no matches or errors.
Why it matters:Misapplying array-contains leads to unexpected empty results or runtime errors.
Quick: do array-contains queries always run fast without indexes? Commit yes or no.
Common Belief:Array-contains queries are always fast because Firebase handles them internally.
Tap to reveal reality
Reality:Without proper indexes, array-contains queries can be slow or fail. Indexes are required for performance.
Why it matters:Ignoring indexing causes slow app performance and poor user experience.
Expert Zone
1
Array-contains queries do not support querying nested arrays or arrays inside maps directly; you must flatten data or restructure documents.
2
The array-contains-any operator is limited to 10 values per query, so large multi-value searches require multiple queries or different data modeling.
3
Firestore indexes array elements as separate entries, so very large arrays can increase index size and cost.
When NOT to use
Avoid array-contains queries when you need to check for multiple values simultaneously or nested arrays; instead, use array-contains-any or redesign your data model with subcollections or maps.
Production Patterns
In production, array-contains queries are often used for tag-based filtering, user membership lists, or feature flags. Developers combine them with pagination and caching to handle large datasets efficiently.
Connections
Relational Database JOINs
Array-contains queries provide a way to filter by list membership similar to how JOINs relate tables by keys.
Understanding array-contains helps grasp how NoSQL databases handle relationships differently than SQL JOINs.
Set Membership in Mathematics
Array-contains queries check if an element belongs to a set (array), mirroring the mathematical concept of set membership.
Recognizing this connection clarifies the logic behind array-contains as a membership test.
Search Engine Inverted Indexes
Array-contains queries use indexes similar to inverted indexes in search engines that map terms to documents.
Knowing this reveals why array-contains queries are efficient and how indexing supports fast lookups.
Common Pitfalls
#1Trying to find documents containing any of multiple values using multiple array-contains filters.
Wrong approach:query.where('tags', 'array-contains', 'red').where('tags', 'array-contains', 'blue')
Correct approach:query.where('tags', 'array-contains-any', ['red', 'blue'])
Root cause:Misunderstanding that only one array-contains filter is allowed per query and that array-contains-any exists for multiple values.
#2Using array-contains on a field that is not an array.
Wrong approach:query.where('status', 'array-contains', 'active') // 'status' is a string, not an array
Correct approach:query.where('status', '==', 'active')
Root cause:Confusing array-contains with equality operator and not verifying field data type.
#3Not creating required indexes for array-contains queries, causing errors or slow queries.
Wrong approach:Running array-contains queries without checking or creating indexes, leading to errors.
Correct approach:Create composite indexes in Firebase console as prompted to support array-contains queries.
Root cause:Ignoring Firebase's indexing requirements and error messages.
Key Takeaways
Array-contains queries let you efficiently find documents where an array field includes a specific value.
They only check for one value at a time and cannot be combined multiple times in one query.
Proper indexing is essential for performance and to avoid query errors.
Understanding array-contains helps you design better data models and queries in Firebase.
Knowing its limits guides you to use alternatives like array-contains-any or data restructuring when needed.

Practice

(1/5)
1.

What does the array-contains query operator do in Firebase Firestore?

easy
A. Finds documents where an array field includes a specific value
B. Finds documents where a string field contains a substring
C. Finds documents where a number field is greater than a value
D. Finds documents where a field is missing

Solution

  1. Step 1: Understand the purpose of array-contains

    This operator is designed to check if an array field in a document contains a specific value.
  2. Step 2: Compare with other query types

    Other options describe different query operators, but only array-contains matches arrays including a value.
  3. Final Answer:

    Finds documents where an array field includes a specific value -> Option A
  4. Quick Check:

    array-contains = finds value in array [OK]
Hint: Remember: array-contains checks for one value inside an array [OK]
Common Mistakes:
  • Confusing array-contains with substring search
  • Using array-contains on non-array fields
  • Thinking it works with multiple values at once
2.

Which of the following is the correct syntax to query documents where the tags array contains the value "urgent"?

const query = firestore.collection('tasks').where(____);
easy
A. "tags", "contains", "urgent"
B. "tags", "==", "urgent"
C. "tags", "array-contains-any", ["urgent"]
D. "tags", "array-contains", "urgent"

Solution

  1. Step 1: Recall the correct operator for single value in array

    The operator is "array-contains" to check if an array includes a specific value.
  2. Step 2: Check syntax format

    The syntax is .where("field", "array-contains", value). "tags", "array-contains", "urgent" matches this exactly.
  3. Final Answer:

    "tags", "array-contains", "urgent" -> Option D
  4. Quick Check:

    Correct syntax uses array-contains [OK]
Hint: Use "array-contains" for single value array queries [OK]
Common Mistakes:
  • Using == instead of array-contains for arrays
  • Confusing array-contains with array-contains-any
  • Using non-existent operator "contains"
3.

Given the following documents in a Firestore collection projects:

[{ id: 1, members: ["alice", "bob"] }, { id: 2, members: ["carol"] }, { id: 3, members: ["bob", "dave"] }]

What will the query firestore.collection('projects').where('members', 'array-contains', 'bob').get() return?

medium
A. Documents with id 2 only
B. Documents with id 1 only
C. Documents with id 1 and 3
D. No documents

Solution

  1. Step 1: Identify documents where 'members' array contains 'bob'

    Document 1 has members ["alice", "bob"] which includes "bob". Document 3 has ["bob", "dave"] which also includes "bob". Document 2 does not.
  2. Step 2: Determine query result

    The query returns documents 1 and 3 because their 'members' arrays contain "bob".
  3. Final Answer:

    Documents with id 1 and 3 -> Option C
  4. Quick Check:

    array-contains 'bob' = docs 1 and 3 [OK]
Hint: Check which arrays include the value exactly [OK]
Common Mistakes:
  • Including documents without the value
  • Confusing array-contains with array-contains-any
  • Assuming partial matches inside strings
4.

What is wrong with this Firestore query?

firestore.collection('orders').where('items', 'array-contains', ['apple', 'banana'])

The items field is an array of strings.

medium
A. You cannot use an array as the value with array-contains
B. The operator should be 'array-contains-any' instead
C. The field 'items' must be a string, not an array
D. The query syntax is correct

Solution

  1. Step 1: Understand array-contains value type

    The 'array-contains' operator expects a single value, not an array, to check inside the array field.
  2. Step 2: Identify correct usage

    Passing an array as the value causes an error. To check multiple values, 'array-contains-any' is used instead.
  3. Final Answer:

    You cannot use an array as the value with array-contains -> Option A
  4. Quick Check:

    array-contains needs single value, not array [OK]
Hint: array-contains accepts only one value, not arrays [OK]
Common Mistakes:
  • Passing an array as the value to array-contains
  • Confusing array-contains with array-contains-any
  • Assuming array-contains works like 'in' operator
5.

You want to find all documents in the events collection where the attendees array contains both "john" and "jane". Which approach is correct?

hard
A. Use a single query with array-contains-any and pass both names
B. Use two queries with array-contains for each name and merge results client-side
C. Use a single query with array-contains and pass an array of both names
D. Use a query with where('attendees', '==', ['john', 'jane'])

Solution

  1. Step 1: Understand limitations of array-contains and array-contains-any

    array-contains checks for one value in array; array-contains-any checks if array contains any of multiple values but not all.
  2. Step 2: Find correct method to get documents containing both values

    Since Firestore does not support querying for multiple values all present in one array in a single query, you must run two queries with array-contains and combine results client-side.
  3. Final Answer:

    Use two queries with array-contains for each name and merge results client-side -> Option B
  4. Quick Check:

    Multiple array-contains queries combined client-side [OK]
Hint: Firestore can't query multiple array-contains in one query [OK]
Common Mistakes:
  • Using array-contains-any expecting all values matched
  • Passing array of values to array-contains
  • Using equality check on arrays
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard