0
0
Firebasecloud~5 mins

Compound queries (multiple where) in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to find data that matches more than one condition at the same time. Compound queries let you ask for documents that meet multiple rules, like finding all users who live in a city and are older than 25.
When you want to find all orders that are both paid and shipped.
When you need to get all users who signed up after a certain date and have a premium account.
When filtering products that are in stock and cost less than a certain amount.
When searching for events that are in a specific location and happening on a specific date.
When you want to combine filters like status and priority in a task list.
Commands
This command queries the 'users' collection for documents where the city is 'New York' and the age is greater than 25. It shows how to use multiple where conditions together.
Terminal
firebase firestore:query --collection=users --where="city==\"New York\"" --where="age>25"
Expected OutputExpected
[ { "name": "Alice", "city": "New York", "age": 30 }, { "name": "Bob", "city": "New York", "age": 28 } ]
--collection - Specifies which collection to search in Firestore.
--where - Adds a filter condition to the query.
This command runs the same compound query but limits the results to 2 documents to avoid too much data at once.
Terminal
firebase firestore:query --collection=users --where="city==\"New York\"" --where="age>25" --limit=2
Expected OutputExpected
[ { "name": "Alice", "city": "New York", "age": 30 }, { "name": "Bob", "city": "New York", "age": 28 } ]
--limit - Limits the number of documents returned.
Key Concept

If you remember nothing else from this pattern, remember: you can combine multiple where filters to find exactly the documents that match all your conditions.

Common Mistakes
Trying to use multiple where filters on different fields without creating the proper composite index.
Firestore requires a composite index for compound queries on multiple fields, otherwise the query will fail.
Create the needed composite index in the Firebase console when prompted, or design your queries to use supported indexes.
Using unsupported operators together in compound queries, like '!=' with other where filters.
Firestore does not support combining certain operators in the same compound query.
Check Firestore documentation for supported operator combinations and adjust your query accordingly.
Summary
Use multiple --where flags to add several conditions to your Firestore query.
Compound queries return documents that meet all the specified conditions.
Limit results with --limit to control how many documents you get back.