Firebase Firestore Querying Filtering Data for Web A Complete Guide
Tags: firebase, javascript, programming
Published: 2021-03-29 15:20:02

Understanding how queries work on the [Firestore](https://firebase.google.com/docs/firestore) Database is one of the valuable skills to have as a Firebase Developer such as the Cloud Firestore is getting more popular than the [real-time database](https://firebase.google.com/docs/database).

In this Firestore tutorial, I will be covering how to do simple CRUD (**Create**, **Read**, **Update** and **Delete**) operations with Firestore Database.

After that, you are going to learn how to make queries using **WHERE** (single/multiple), **ORDERBY**, and **LIMIT** filters.

Then, I will guide you through how to get sub-collections data Collection Group queries which is one of the new features at the time of this post.

Finally, I am going to be teaching you how to split queries when you have a large collection of documents using pagination with Query Cursor function for a better experience and to save money.

Sounds interesting! 😯… A lot to cover!

Let’s get started. 🚀

Feel free to jump into any of the sections below.

- [Add Data to Firestore](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#add-document-to-cloud-firestore)
- [Firebase Update Document](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#update-a-document-firestore)
- [Delete Data from Cloud Firestore](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#delete-data-from-cloud-firestore)
- [Get Documents Data from Firestore Database](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#get-documents-from-firestore-database)
- [Get A Single Document Data](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#get-a-document-from-firestore)
- [Get Data from Sub-collection](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#get-data-from-firestore-subcollection)
- [Firestore Single/Multiple Where Query Filter](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#single-multiple-where-firestore-query)
- [OrderBy and Limit Filters](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#order-limit-firestore-query)
- [Collection Group Queries](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#collection-group-queries-firestore)
- [Firestore Pagination Queries using Query Cursors](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#pagination-with-query-cursors-firestore)
- [Setting up a Firebase App on the Firebase Console](https://www.softauthor.com/learn-to-build-firebase-crud-app-with-javascript-part01-reading-data/#setting-up-a-firebase-app-on-the-firebase-console)
- [Enable Read and Write Permission to the Firebase Database](https://www.softauthor.com/learn-to-build-firebase-crud-app-with-javascript-part01-reading-data/#enable-read-and-write-permission-to-the-firebase-database)

✅ Recommended
{% youtube 31MVIwvstzs %}

##Add/Create A Document To Cloud Firestore

There are two ways to create/add a new document to the Cloud Firestore, which are:

- add()
- set()

Let’s take a look at **add()** method sample code.

```javascript
const db = firebase.firestore()
db.collection("users").add({
    name: "Anbu Selvan",
    email: "anbu.selvan@email.com",
    age: 25
})
```

>To run the sample code in your project, you will need to add Firebase to your project.

First, get a reference to the Firestore database using **firestore()** method and store it in **db**.

Then, obtain a reference to the users collection by invoking **collection()** method on the **db** object.

Finally, run **add()** method by passing new data as a JavaScript object.

That’s it.

![Alt text of image](https://www.softauthor.com/wp-content/uploads/2019/07/firestore-add-data.png)

Let’s take a look at the **set()** method.

As you can see below, the **set()** method is very similar to **add()**.

```javascript
db.collection("users")
.doc()
.set({ 
    name: "Anbu Selvan", 
    email: "anbu.selvan@email.com",
    age: 25
})
```
The only difference is that you can add a document to a collection directly using **add()** method, but for the **set()** method you need to explicitly specify the document identifier by invoking **doc()**.

If you do not specify a document identifier, it will be created.

Under the hood, both **set()** and **add()** are working very similarly according to the [Firestore Documentation](https://firebase.google.com/docs/firestore/manage-data/add-data).

I prefer to use **set()** over **add()** because I can use a single method to add or update data. 🙂

>✅ Recommended Full Video Course
>[Firebase + JavaScript: A Complete Guide](https://www.udemy.com/course/full-stack-firebase/?ranMID=39197&ranEAID=nsrC6aUWa3g&ranSiteID=nsrC6aUWa3g-Q6FRNxCWh1xHmyMaMRfjtQ&utm_source=aff-campaign&utm_medium=udemyads&LSNPUBID=nsrC6aUWa3g)

##Update A Document Data to Cloud Firestore

There are two options to update existing data.

- set()
- update()

###Overwriting A Document using set()

When you want to overwrite or completely replace an existing document, you can easily do that by using the **set()** method by passing an existing auto-generated document identifier as an argument to the **doc()** method.

```javascript
db.collection("users")
   .doc("3P86VJxcpBK0D0lsAyYx")
    .set({
        name: "Lee Kuan",
});
```

![Alt text of image](https://www.softauthor.com/wp-content/uploads/2019/07/firestore-set-overwrite-data.png)

There are some cases where you will need to just update (override) one or more fields rather than replacing the whole document.

This can also be done by **set()** method as well.

```javascript
db.collection("users")
.doc("3P86VJxcpBK0D0lsAyYx")
.set(
    {
        name: "Anbu Selvan",
        age: 25
    },
    { merge: true }
);
```
The above code is very similar to the previous one, with the only difference being it has a JavaScript object {merge: true} as a second argument to the **set()** method which will prevent overwriting an entire document.

At this stage, the **set()** method will only update with new values to the targetted document if the **name** and **age** fields exist.

Otherwise, the missing fields will be created.

In this case, the value of **name** will be replaced from Lee Kuan to Anbu Selvan and the **age** field will be added to the document as it did not exist before.

![Alt text of image](https://www.softauthor.com/wp-content/uploads/2019/07/firestore-override-data-update-set.png)

###Overriding A Document using update()

The **update()** method is very similar to **set()** without the second argument and is pretty straightforward.

```javascript
db.collection("users")
.doc("3P86VJxcpBK0D0lsAyYx")
.update(
    {
        name: "Anbu Selvan",
        email: "anbu.selvan@email.com",
    },
);
```

You must provide an auto-generated ID as an argument to the **doc()** when using **update()** method to have it work.

>✅ Recommended Full Video Course
>[Firebase Authentication & Security: A Complete Guide](https://www.udemy.com/course/firebase-authentication/?ranMID=39197&ranEAID=nsrC6aUWa3g&ranSiteID=nsrC6aUWa3g-4P_Su.VZLAz5JQgy70PTxg&utm_source=aff-campaign&utm_medium=udemyads&LSNPUBID=nsrC6aUWa3g)


##Delete Document from Cloud Firestore

###Delete A Field From A Document on the Firestore Database

You can delete an entire document from Cloud Firestore using the **delete()** method by passing its auto-generated ID as an argument to the **doc()** method.

```javascript
db.collection("users")
.doc("3P86VJxcpBK0D0lsAyYx")
.delete()
.then(function () { 
    console.log("Document successfully deleted!"); 
}).catch(
    function(error) { 
    console.error("Error removing document: ", error); 
});
```
>One more thing I want to point out here is that sub-collections won’t be deleted when you delete the parent document.

###Delete A Field From A Document on the Firestore Database

To delete a specific field from a document, use the **update()** method and inside it add the field that you want to delete as a javascript object and set firebase.firestore.FieldValue.delete() as a value of it.

```javascript
db.collection("users")
.doc("3P86VJxcpBK0D0lsAyYx")
.update({
    email.firestore.FieldValue.delete()
})
```

Pretty straightforward.

Before getting into retrieving data from the Firestore Database, let’s add some data to the Firestore Database calling the following function once.

```javascript
addUsersToFirestore() {
    var users = [{
            name: "Raja",
            email: "raja.tamil@email.com",
            createdAt: new Date("2019-01-01 12:08:00")
        },
        {
            name: "Arivu",
            email: "arivu.selvan@email.com",
            createdAt: new Date("2018-01-23 09:13:00")
        }, {
            name: "Mike",
            email: "mike.author@email.com",
            createdAt: new Date("2018-08-08 06:37:00")
        }, {
            name: "Praba",
            email: "praba.karan@email.com",
            createdAt: new Date("2018-10-09 18:26:00")
        },
        {
            name: "Muhammad",
            email: "muhammad.ali@email.com",
            createdAt: new Date("2018-03-13 12:13:00")
        }

    ];
    const db = firebase.firestore();
    users.forEach(user => {
        db.collection("users").doc().set(user);
    });
}
```
If everything goes well, you should have a collection called **users** with five documents.

![Alt text of image](https://www.softauthor.com/wp-content/uploads/2019/07/add-users-collection-to-firestore.png)

>Recommended
>[Build A Secure To-Do App with Vue + Firestore Authentication](https://www.softauthor.com/vue-firestore-crud-app-authentication/)

[Continue Reading...](https://www.softauthor.com/firestore-querying-filtering-data-for-web/#pagination-with-query-cursors-firestore)