DEV Community

loading...
Cover image for Firebase Firestore Querying Filtering Data for Web ← A Complete Guide

Firebase Firestore Querying Filtering Data for Web ← A Complete Guide

hirajatamil profile image Raja Tamil Updated on ・6 min read

Understanding how queries work on the 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.

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.

✅ Recommended
IMAGE ALT TEXT HERE

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.

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

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

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

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

db.collection("users")
.doc()
.set({ 
    name: "Anbu Selvan", 
    email: "anbu.selvan@email.com",
    age: 25
})
Enter fullscreen mode Exit fullscreen mode

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.

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

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.

db.collection("users")
   .doc("3P86VJxcpBK0D0lsAyYx")
    .set({
        name: "Lee Kuan",
});
Enter fullscreen mode Exit fullscreen mode

Alt text of image

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.

db.collection("users")
.doc("3P86VJxcpBK0D0lsAyYx")
.set(
    {
        name: "Anbu Selvan",
        age: 25
    },
    { merge: true }
);
Enter fullscreen mode Exit fullscreen mode

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

Overriding A Document using update()

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

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

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

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.

db.collection("users")
.doc("3P86VJxcpBK0D0lsAyYx")
.delete()
.then(function () { 
    console.log("Document successfully deleted!"); 
}).catch(
    function(error) { 
    console.error("Error removing document: ", error); 
});
Enter fullscreen mode Exit fullscreen mode

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.

db.collection("users")
.doc("3P86VJxcpBK0D0lsAyYx")
.update({
    email.firestore.FieldValue.delete()
})
Enter fullscreen mode Exit fullscreen mode

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.

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);
    });
}
Enter fullscreen mode Exit fullscreen mode

If everything goes well, you should have a collection called users with five documents.

Alt text of image

Recommended
Build A Secure To-Do App with Vue + Firestore Authentication

Continue Reading...

Discussion (0)

pic
Editor guide