How to Use equalTo in Firebase Realtime Database Queries
Use
equalTo(value) in Firebase Realtime Database queries to find data entries where a specific child key equals value. Combine it with orderByChild() to specify which child key to filter by. This returns only matching records from your database.Syntax
The equalTo() method filters data to return only nodes where the specified child key matches the given value exactly. It must be used with orderByChild() to specify the child key to compare.
orderByChild('childKey'): Sorts data by the child key you want to filter.equalTo(value): Filters data to only include nodes where the child key equalsvalue.
javascript
firebase.database().ref('path').orderByChild('childKey').equalTo(value).on('value', snapshot => { // handle filtered data });
Example
This example shows how to get all users whose age is exactly 25 from the Realtime Database.
javascript
const dbRef = firebase.database().ref('users'); dbRef.orderByChild('age').equalTo(25).on('value', snapshot => { const users = snapshot.val(); console.log(users); });
Output
{
"user1": {"name": "Alice", "age": 25},
"user3": {"name": "Charlie", "age": 25}
}
Common Pitfalls
Common mistakes when using equalTo() include:
- Not using
orderByChild()beforeequalTo(), which causes the query to fail. - Using
equalTo()on a key that does not exist or has different data types, resulting in no matches. - Expecting partial matches;
equalTo()only matches exact values.
javascript
/* Wrong: missing orderByChild */ firebase.database().ref('users').equalTo(25).on('value', snapshot => { console.log(snapshot.val()); }); /* Right: use orderByChild before equalTo */ firebase.database().ref('users').orderByChild('age').equalTo(25).on('value', snapshot => { console.log(snapshot.val()); });
Quick Reference
Summary tips for using equalTo() in Firebase Realtime Database:
- Always use
orderByChild()beforeequalTo(). equalTo()matches exact values only, no partial or range matches.- Works with strings, numbers, and booleans as values.
- Use
on('value')oronce('value')to read filtered data.
Key Takeaways
Use equalTo only after orderByChild to filter by a child key's exact value.
equalTo matches exact values; it does not support partial or range queries.
Always verify the child key exists and data types match for expected results.
Use on('value') or once('value') to listen for or fetch filtered data snapshots.
Common errors come from missing orderByChild or mismatched data types.