Firestore Queries-A Practical Demo

Varun Kumar S

1 min read

In my previous blog, we learned the key capabilities and advantages of Firestore. Now, allow me to guide you through the four basic Firestore queries that are used to do the CRUD operations with examples.

They are,

  • add()
  • get()
  • update()
  • delete()

Consider a Firestore collection with the name Patients. It will contain the documents of the patients.We can find the data of individual patients using their unique IDs.

A visual representation of Firestore Collection and documents

Add

Now we will be using add() to write a document into the Patients collection.
It does the C’s work in CRUD.

We can use the add() method as I did below,

Add() method demo

After running the above method successfully, the Firestore Collection will look something like below.

Patients collection after using the add() method

With the add() method successfully used, let’s get to the next one.

Get

We can use the get() method to read a document from the collection or Read the whole collection.
This does the R’s work in CRUD

Reading- a document:

We can read an individual document using its unique id.

get() method demo (single document)

From the get() method we can get a Document Snapshot. A document snapshot contains data like the fields, its Id, metadata, etc.

Read- a Collection:

Reading a collection is different from reading a document. It returns a Query Snapshot, which has all the document snapshots, metadata, etc.

get() method demo (whole collection)

Update

We use update() method to manipulate the data in a single document.
This does the U’s work in CRUD.

Lets try to change the bloodGroup of patient-1 to B+ with update method.

update() method demo

After updating the Firebase document will look as below.

After updating blood group of patient-1

Delete

The Delete method can be used to delete a document or to delete a field inside a document.
It does the D’s work in CRUD.

Now lets try deleting the document of patient-1,

Delete document demo

After deleting the document the Firestore collection will look something like below.

After deleting the document of patient-1

So, that’s how we do the CRUD operation in Firestore.

Thanks…

Bye!!

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *