How to Use the in Operator in Firestore Queries
Use the
in operator in Firestore queries to find documents where a field matches any value from a list of values. It works by passing an array of values to where() with the operator set to in. This returns documents with the field equal to any of those values.Syntax
The in operator is used inside a Firestore query with the where() method. It takes three arguments:
- field: The document field to check.
- operator: The string
"in"to specify the operator. - values: An array of values to match against the field.
This query returns documents where the field's value matches any value in the array.
javascript
const query = firestore.collection('users').where('status', 'in', ['active', 'pending']);
Example
This example queries a Firestore collection named users to find all users whose role field is either "admin" or "editor". It then logs their names.
javascript
import { getFirestore, collection, query, where, getDocs } from 'firebase/firestore'; const firestore = getFirestore(); async function getUsersByRole() { const usersRef = collection(firestore, 'users'); const q = query(usersRef, where('role', 'in', ['admin', 'editor'])); const querySnapshot = await getDocs(q); querySnapshot.forEach((doc) => { console.log(doc.id, '=>', doc.data().name); }); } getUsersByRole();
Output
user123 => Alice
user456 => Bob
Common Pitfalls
Common mistakes when using the in operator include:
- Passing more than 10 values in the array, which Firestore does not allow.
- Using
inon fields that are arrays themselves, which requiresarray-contains-anyinstead. - Trying to combine
inwith other inequality operators on the same field.
Always ensure the array has 10 or fewer values and the field is a simple value, not an array.
javascript
/* Wrong: More than 10 values */ const qWrong = query(usersRef, where('status', 'in', ['a','b','c','d','e','f','g','h','i','j','k'])); /* Right: 10 or fewer values */ const qRight = query(usersRef, where('status', 'in', ['a','b','c','d','e','f','g','h','i','j']));
Quick Reference
Tips for using the in operator:
- Use
into match a field against multiple values. - Limit the array to 10 values max.
- Use
array-contains-anyif the field is an array. - Combine
inwith other filters carefully.
Key Takeaways
Use the
in operator with where() to match a field against multiple values.The array of values for
in must have 10 or fewer items.Do not use
in on array fields; use array-contains-any instead.Avoid combining
in with other inequality filters on the same field.The
in operator helps simplify queries that need to check multiple possible values.