0
0
Firebasecloud~3 mins

Why Array-contains queries in Firebase? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could find any item inside a list instantly, without flipping through every page?

The Scenario

Imagine you have a list of friends and each friend has a list of hobbies stored in a big notebook. Now, you want to find all friends who like "soccer". You start flipping through every page, reading each hobby list one by one.

The Problem

This manual search is slow and tiring. You might miss some friends or make mistakes. If the notebook grows bigger, it takes even longer. Doing this by hand is frustrating and wastes time.

The Solution

Array-contains queries let you ask the notebook directly: "Show me all friends whose hobbies include 'soccer'." The system quickly finds the right pages without reading everything, saving time and avoiding errors.

Before vs After
Before
for friend in friends:
    if 'soccer' in friend.hobbies:
        print(friend.name)
After
db.collection('friends').where('hobbies', 'array-contains', 'soccer').get().then(querySnapshot => {
  querySnapshot.forEach(doc => {
    console.log(doc.id, ' => ', doc.data());
  });
});
What It Enables

You can instantly find all records containing a specific item inside an array, making searches fast and simple.

Real Life Example

A social app wants to show users who like a certain sport or music genre. Using array-contains queries, it quickly finds and displays those users without scanning the entire database.

Key Takeaways

Manual searching through arrays is slow and error-prone.

Array-contains queries let you search inside arrays efficiently.

This makes your app faster and your code cleaner.