Retrieving Data with Firebase Realtime Database for C++

This document covers the basics of retrieving data and how to order and filterFirebase data.

Before you begin

Make sure you've setup your app and can access the database as covered intheGet Started guide.

Retrieving Data

Firebase data is retrieved by either a one time call toGetValue() orattaching to aValueListener on aFirebaseDatabase reference. The valuelistener is called once for the initial state of the data and again anytime thedata changes.

Get a DatabaseReference

To write data to the Database, you need an instance ofDatabaseReference:

// Get the root reference location of the database.firebase::database::DatabaseReferencedbref=database->GetReference();

Read data once

You can use theGetValue() method to read a static snapshot of thecontents at a given path once. The task result will contain a snapshotcontaining all data at that location, including child data. If there is no data,the snapshot returned isnull.

firebase::Future&ltfirebase::database::DataSnapshot&gtresult=dbRef.GetReference("Leaders").GetValue();

At the point the request has been made but we have to wait for the Future tocomplete before we can read the value. Since games typically run in a loop, andare less callback driven than other applications, you'll typically poll forcompletion.

// In the game loop that polls for the result...if(result.status()!=firebase::kFutureStatusPending){if(result.status()!=firebase::kFutureStatusComplete){LogMessage("ERROR: GetValue() returned an invalid result.");// Handle the error...}elseif(result.error()!=firebase::database::kErrorNone){LogMessage("ERROR: GetValue() returned error %d: %s",result.error(),result.error_message());// Handle the error...}else{firebase::database::DataSnapshotsnapshot=result.result();// Do something with the snapshot...}}

This shows some basic error checking, see thefirebase::Future reference for moreinformation on error checking, and ways to determine when the result is ready.

Listen for events

You can add listeners to subscribe on changes to data:

ValueListener base class

CallbackTypical usage
OnValueChangedRead and listen for changes to the entire contents of a path.

OnChildListener base class

OnChildAddedRetrieve lists of items or listen for additions to a list of items. Suggested use withOnChildChanged andOnChildRemoved to monitor changes to lists.
OnChildChangedListen for changes to the items in a list. Use withOnChildAdded andOnChildRemoved to monitor changes to lists.
OnChildRemovedListen for items being removed from a list. Use withOnChildAdded andOnChildChanged to monitor changes to lists.
OnChildMovedListen for changes to the order of items in an ordered list.OnChildMoved callbacks always follow theOnChildChanged callbacks due to the item's order changing (based on your current order-by method).

ValueListener class

You can use theOnValueChanged callbacks to subscribe to changes to thecontents at a given path. This callback is triggered once when the listener isattached and again every time the data, including children, changes. Thecallback is passed a snapshot containing all data at that location, includingchild data. If there is no data, the snapshot returned isnull.

Important: TheOnValueChanged event is called every time data is changed atthe specified database reference, including changes to children. To limit thesize of your snapshots, attach only at the highest level needed for watchingchanges. For example, attaching a listener to the root of your databaseis not recommended.

The following example demonstrates a game retrieving the scores of a leaderboardfrom the database:

classLeadersValueListener:publicfirebase::database::ValueListener{public:voidOnValueChanged(constfirebase::database::DataSnapshot&snapshot)override{// Do something with the data in snapshot...}voidOnCancelled(constfirebase::database::Error&error_code,constchar*error_message)override{LogMessage("ERROR: LeadersValueListener canceled: %d: %s",error_code,error_message);}};// Elsewhere in the code...LeadersValueListener*listener=newLeadersValueListener();firebase::Future&ltfirebase::database::DataSnapshot&gtresult=dbRef.GetReference("Leaders").AddValueListener(listener);

TheFuture&ltDataSnapshot&gt result contains the data at the specified locationin the database at the time of the event. Callingvalue() on a snapshotreturns aVariant representing the data.

In this example, theOnCancelled method is also overridden to see if the readis canceled. For example, a read can be canceled if the client doesn't havepermission to read from a Firebase database location. Thedatabase::Error willindicate why the failure occurred.

ChildListener class

Child events are triggered in response to specific operations that happen to thechildren of a node from an operation such as a new child added through thePushChild() method or a child being updated through theUpdateChildren()method. Each of these together can be useful for listening to changes to aspecific node in a database. For example, a game might use these methodstogether to monitor activity in the comments of a game session, as shown below:

classSessionCommentsChildListener:publicfirebase::database::ChildListener{public:voidOnChildAdded(constfirebase::database::DataSnapshot&snapshot,constchar*previous_sibling)override{// Do something with the data in snapshot ...}voidOnChildChanged(constfirebase::database::DataSnapshot&snapshot,constchar*previous_sibling)override{// Do something with the data in snapshot ...}voidOnChildRemoved(constfirebase::database::DataSnapshot&snapshot)override{// Do something with the data in snapshot ...}voidOnChildMoved(constfirebase::database::DataSnapshot&snapshot,constchar*previous_sibling)override{// Do something with the data in snapshot ...}voidOnCancelled(constfirebase::database::Error&error_code,constchar*error_message)override{LogMessage("ERROR: SessionCommentsChildListener canceled: %d: %s",error_code,error_message);}};// elsewhere ....SessionCommentsChildListener*listener=newSessionCommentsChildListener();firebase::Future&ltfirebase::database::DataSnapshot&gtresult=dbRef.GetReference("GameSessionComments").AddChildListener(listener);

TheOnChildAdded callback is typically used to retrieve a list ofitems in a Firebase database. TheOnChildAdded callback is called oncefor each existing child and then again every time a new child is added to thespecified path. The listener is passed a snapshot containing the new child'sdata.

TheOnChildChanged callback is called any time a child node is modified.This includes any modifications to descendants of the child node. It istypically used in conjunction with theOnChildAdded andOnChildRemovedcalls to respond to changes to a list of items. The snapshot passed to thelistener contains the updated data for the child.

TheOnChildRemoved callback is triggered when an immediate child is removed.It is typically used in conjunction with theOnChildAdded andOnChildChanged callbacks. The snapshot passed to the callback containsthe data for the removed child.

TheOnChildMoved callback is triggered whenever theOnChildChangedcall is raised by an update that causes reordering of the child. It isused with data that is ordered withOrderByChild orOrderByValue.

Sorting and filtering data

You can use theRealtime DatabaseQuery class to retrieve data sorted bykey, by value, or by value of a child. You can also filterthe sorted result to a specific number of results or a range of keys orvalues.

Note: Filtering and sorting can be expensive, especially when done on theclient. If your app uses queries, define the.indexOn rule to index thosekeys on the server and improve query performance as described inIndexing Your Data.

Sort data

To retrieve sorted data, start by specifying one of the order-by methods todetermine how results are ordered:

MethodUsage
OrderByChild()Order results by the value of a specified child key.
OrderByKey()Order results by child keys.
OrderByValue()Order results by child values.

You can only useone order-by method at a time. Calling an order-by methodmultiple times in the same query throws an error.

The following example demonstrates how you could subscribe to a scoreleaderboard ordered by score.

firebase::database::Queryquery=dbRef.GetReference("Leaders").OrderByChild("score");// To get the resulting DataSnapshot either use query.GetValue() and poll the// future, or use query.AddValueListener() and register to handle the// OnValueChanged callback.

This defines afirebase::Query that when combined with aValueListener synchronizes the client with the leaderboardin the database, ordered by the score of each entry.You can read more about structuring your data efficiently inStructure Your Database.

The call to theOrderByChild() method specifies the child key to order theresults by. In this case, results are sorted by the value of the"score"value in each child. For more information on how other data types are ordered,seeHow query data is ordered.

Filtering data

To filter data, you can combine any of the limit or range methods with anorder-by method when constructing a query.

MethodUsage
LimitToFirst()Sets the maximum number of items to return from the beginning of the ordered list of results.
LimitToLast()Sets the maximum number of items to return from the end of the ordered list of results.
StartAt()Return items greater than or equal to the specified key or value depending on the order-by method chosen.
EndAt()Return items less than or equal to the specified key or value depending on the order-by method chosen.
EqualTo()Return items equal to the specified key or value depending on the order-by method chosen.

Unlike the order-by methods, you can combine multiple limit or range functions.For example, you can combine theStartAt() andEndAt() methods to limitthe results to a specified range of values.

Even when there is only a single match for the query, the snapshot is stilla list; it just contains a single item.

Limit the number of results

You can use theLimitToFirst() andLimitToLast() methods to set amaximum number of children to be synced for a given callback. For example, ifyou useLimitToFirst() to set a limit of 100, you initially only receive upto 100OnChildAdded callbacks. If you have fewer than 100 items stored in yourFirebase database, anOnChildAdded callback fires for each item.

As items change, you receiveOnChildAdded callbacks for items that enter thequery andOnChildRemoved callbacks for items that drop out of it so thatthe total number stays at 100.

For example, the code below returns the top score from a leaderboard:

firebase::database::Queryquery=dbRef.GetReference("Leaders").OrderByChild("score").LimitToLast(1);// To get the resulting DataSnapshot either use query.GetValue() and poll the// future, or use query.AddValueListener() and register to handle the// OnValueChanged callback.

Filter by key or value

You can useStartAt(),EndAt(), andEqualTo() to choose arbitrarystarting, ending, and equivalence points for queries. This can be useful forpaginating data or finding items with children that have a specific value.

How query data is ordered

This section explains how data is sorted by each of the order-by methods in theQuery class.

OrderByChild

When usingOrderByChild(), data that contains the specified child key isordered as follows:

  1. Children with anull value for the specified child key come first.
  2. Children with a value offalse for the specified child key come next. If multiple children have a value offalse, they are sortedlexicographically by key.
  3. Children with a value oftrue for the specified child key come next. If multiple children have a value oftrue, they are sorted lexicographically by key.
  4. Children with a numeric value come next, sorted in ascending order. If multiple children have the same numerical value for the specified child node, they are sorted by key.
  5. Strings come after numbers and are sorted lexicographically in ascending order. If multiple children have the same value for the specified child node, they are ordered lexicographically by key.
  6. Objects come last and are sorted lexicographically by key in ascending order.

OrderByKey

When usingOrderByKey() to sort your data, data is returned in ascending orderby key.

  1. Children with a key that can be parsed as a 32-bit integer come first, sorted in ascending order.
  2. Children with a string value as their key come next, sorted lexicographically in ascending order.

OrderByValue

When usingOrderByValue(), children are ordered by their value. The orderingcriteria are the same as inOrderByChild(), except the value of the node isused instead of the value of a specified child key.

Next Steps

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-17 UTC.