Learn how to filter Firestore documents using array-contains. Follow our step-by-step guide to set up Firebase, add data, query, and secure your database.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up Your Firebase Firestore
Ensure that you have Firebase set up in your project. If you haven't done so, follow these steps:
Step 2: Initialize Firebase in Your Project
First, you need to integrate Firebase into your application. Add Firebase to your web application:
Include Firebase SDK in your index.html:
```html
```
Initialize Firebase in your JavaScript file (e.g., app.js):
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "YOUR_SENDER_ID",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
Step 3: Add Documents with an Array Field to Firestore
Before you can filter documents with array-contains, ensure you have documents that contain an array field. Add some dummy data to Firestore:
const docRef = db.collection('users').doc('user1');
docRef.set({
name: 'John Doe',
hobbies: ['reading', 'hiking', 'swimming']
});
const docRef2 = db.collection('users').doc('user2');
docRef2.set({
name: 'Jane Smith',
hobbies: ['swimming', 'cycling']
});
Step 4: Query Firestore with array-contains
To filter documents by values inside an array, use the array-contains filter. For example, if you want to find users who have "swimming" as a hobby:
db.collection('users')
.where('hobbies', 'array-contains', 'swimming')
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${JSON.stringify(doc.data())}`);
});
})
.catch((error) => {
console.error('Error fetching documents: ', error);
});
Step 5: Run & Test Your Query
Step 6: Secure Your Firestore Database
When you're moving to production, ensure your database is secure. In the Firestore rules, modify access levels accordingly:
// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
match /databases/{database}/documents {
match /{document=\*\*} {
allow read, write: if request.auth != null;
}
}
}
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.