/firebase-tutorials

How to filter documents by array-contains in Firestore?

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.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to filter documents by array-contains in Firestore?

 

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:

  • Go to the Firebase Console.
  • Click on "Get Started" and create a new project (or choose an existing one).
  • In the project dashboard, select "Firestore Database" from the left menu.
  • Click on "Create Database" and select "Start in Test Mode" (or "Start in Production Mode" if you want to specify security rules).

 

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

 

  • Open your project in a web server or local server environment.
  • Check the console to see if the documents are filtered correctly based on 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;
    }
  }
}

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022