Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch particular fields from Firebase database

I am working on firebase project, where i stored user info within a Table. Now my requirement is to show all user's in a Table. Here is my database snapshot

enter image description here

I can fetch all user's with from database using

       if let user = FIRAuth.auth()?.currentUser {
            self.ref?.child("Users").observeSingleEvent(of: .value, with: { (snapshot) in
                // Get user value
                let value = snapshot.value as? NSDictionary
                let name = value?["name"] as? String ?? ""
                let email = value?["email"] as? String ?? ""


            // ...
            }) { (error) in
                print(error.localizedDescription)
            }
        }

Above code return me users array with bod, email, name, gender. But i want to fetch only email and name of users. Is there a way to fetch only specified fields from Database ?

like image 311
Surjeet Singh Avatar asked Jul 05 '17 07:07

Surjeet Singh


People also ask

How do I get data from Firebase database?

Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.

How do you filter data in Firebase Realtime Database?

We can filter data in one of three ways: by child key, by key, or by value. A query starts with one of these parameters, and then must be combined with one or more of the following parameters: startAt , endAt , limitToFirst , limitToLast , or equalTo .

How do I extract data from Firebase to excel?

Step 1: Authenticate Microsoft Excel and Firebase / Firestore. Step 2: Pick one of the apps as a trigger, which will kick off your automation. Step 3: Choose a resulting action from the other app. Step 4: Select the data you want to send from one app to the other.


1 Answers

When you read a node, you'll have to retrieve its entire content. So, there is no way to fetch only specific fields from the data returned on reading a path.

Having said that, if it's possible for your use case, I would suggest you to denormalise data with the purpose of queries that only retrieve the information that you need.

For doing that, you can have a separate node that can be called something like Users-NameandEmailList. Now, in this table, have user uids as your child keys, and each entry shall have only a an email and name field.

Something like this :-

Users-NameandEmailList :{

       user1key :{
             name : "ABC"
             email : "[email protected]"
                 },
       user2key : {..},

                        }

I agree that this could lead to replication of data, but if you want to minimise download redundancy and optimise for speed, then this is the way to go!

like image 86
Rohan Stark Avatar answered Oct 16 '22 20:10

Rohan Stark