Retrieving Data Stay organized with collections Save and categorize content based on your preferences.
This document covers the basics of retrieving data and how to order and filterFirebase data.
Before you begin
Before you can useRealtime Database,you need to:
Register your Unity project and configure it to use Firebase.
If your Unity project already uses Firebase, then it's alreadyregistered and configured for Firebase.
If you don't have a Unity project, you can download asample app.
Add theFirebaseUnity SDK (specifically,
FirebaseDatabase.unitypackage) toyour Unity project.
Note that adding Firebase to your Unity project involves tasks both in theFirebase console and in your open Unity project(for example, you download Firebase config files from the console, then movethem into your Unity project).
Retrieving Data
Firebase data is retrieved by either a one time call to GetValueAsync() orattaching to an event on aFirebaseDatabase reference. The event listener iscalled once for the initial state of the data and again anytime the data changes.
Get a DatabaseReference
To read data from the database, you need an instance ofDatabaseReference:
usingFirebase;usingFirebase.Database;usingFirebase.Extensions.TaskExtension;// for ContinueWithOnMainThreadpublicclassMyScript:MonoBehaviour{voidStart(){// Get the root reference location of the database.DatabaseReferencereference=FirebaseDatabase.DefaultInstance.RootReference;}}
Read data once
You can use theGetValueAsyncmethod to read a static snapshot of thecontents at a given path once. The task result will contain asnapshotcontaining all data at that location, including child data. If there is no data,the snapshot returned isnull.
FirebaseDatabase.DefaultInstance.GetReference("Leaders").GetValueAsync().ContinueWithOnMainThread(task=>{if(task.IsFaulted){// Handle the error...}elseif(task.IsCompleted){DataSnapshotsnapshot=task.Result;// Do something with snapshot...}});
Listen for events
You can add event listeners to subscribe on changes to data:
| Event | Typical usage |
|---|---|
ValueChanged | Read and listen for changes to the entire contents of a path. |
ChildAdded | Retrieve lists of items or listen for additions to a list of items. Suggested use withChildChanged andChildRemoved to monitor changes to lists. |
ChildChanged | Listen for changes to the items in a list. Use withChildAdded andChildRemoved to monitor changes to lists. |
ChildRemoved | Listen for items being removed from a list. Use withChildAdded andChildChanged to monitor changes to lists. |
ChildMoved | Listen for changes to the order of items in an ordered list.ChildMoved events always follow theChildChanged event that caused the item's order to change (based on your current order-by method). |
ValueChanged event
You can use theValueChangedevent to subscribe on changes of the contents at a given path. This event istriggered once when the listener is attached and again every time the data,including children, changes. The event callback is passed a snapshot containingall data at that location, including child data. If there is no data, thesnapshot returned isnull.
ValueChanged event is raised 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 an event listener to the root of your databaseis not recommended.The following example demonstrates a game retrieving the scores of a leaderboardfrom the database:
FirebaseDatabase.DefaultInstance.GetReference("Leaders").ValueChanged+=HandleValueChanged;}voidHandleValueChanged(objectsender,ValueChangedEventArgsargs){if(args.DatabaseError!=null){Debug.LogError(args.DatabaseError.Message);return;}// Do something with the data in args.Snapshot}
ValueChangedEventArgs contains aDataSnapshot that contains the data at thespecified location in the database at the time of the event. CallingValueon a snapshot returns aDictionary<string, object> representing the data.If no data exists at the location, callingValue returnsnull.
In this example,args.DatabaseError is also examined to see if the read iscanceled. For example, a read can be canceled if the client doesn't havepermission to read from a Firebase database location. TheDatabaseError will indicate why the failure occurred.
You can later unsubscribe from the event using anyDatabaseReference that hasthe same path.DatabaseReference instances are ephemeral and can be thoughtof as a way to access any path and query.
FirebaseDatabase.DefaultInstance.GetReference("Leaders").ValueChanged-=HandleValueChanged;// unsubscribe from ValueChanged.}
Child events
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 thePush()method or a child being updated through theUpdateChildrenAsync()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:
varref=FirebaseDatabase.DefaultInstance.GetReference("GameSessionComments");ref.ChildAdded+=HandleChildAdded;ref.ChildChanged+=HandleChildChanged;ref.ChildRemoved+=HandleChildRemoved;ref.ChildMoved+=HandleChildMoved;}voidHandleChildAdded(objectsender,ChildChangedEventArgsargs){if(args.DatabaseError!=null){Debug.LogError(args.DatabaseError.Message);return;}// Do something with the data in args.Snapshot}voidHandleChildChanged(objectsender,ChildChangedEventArgsargs){if(args.DatabaseError!=null){Debug.LogError(args.DatabaseError.Message);return;}// Do something with the data in args.Snapshot}voidHandleChildRemoved(objectsender,ChildChangedEventArgsargs){if(args.DatabaseError!=null){Debug.LogError(args.DatabaseError.Message);return;}// Do something with the data in args.Snapshot}voidHandleChildMoved(objectsender,ChildChangedEventArgsargs){if(args.DatabaseError!=null){Debug.LogError(args.DatabaseError.Message);return;}// Do something with the data in args.Snapshot}
TheChildAddedevent is typically used to retrieve a list ofitems in a Firebase database. TheChildAdded event is raised 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.
TheChildChangedevent is raised any time a child node is modified.This includes any modifications to descendants of the child node. It istypically used in conjunction with theChildAdded andChildRemovedevents to respond to changes to a list of items. The snapshot passed to theevent listener contains the updated data for the child.
TheChildRemovedevent is triggered when an immediate child is removed.It is typically used in conjunction with theChildAdded andChildChanged callbacks. The snapshot passed to the event callback containsthe data for the removed child.
TheChildMovedevent is triggered whenever theChildChangedevent 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.
.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:
| Method | Usage |
|---|---|
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 on a scoreleaderboard ordered by score.
FirebaseDatabase.DefaultInstance.GetReference("Leaders").OrderByChild("score").ValueChanged+=HandleValueChanged;}voidHandleValueChanged(objectsender,ValueChangedEventArgsargs){if(args.DatabaseError!=null){Debug.LogError(args.DatabaseError.Message);return;}// Do something with the data in args.Snapshot}
This defines a query that when combined with avaluechanged event listenersynchronizes the client with the leaderboard in the database, ordered by thescore 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.
| Method | Usage |
|---|---|
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 100ChildAdded callbacks. If you have fewer than 100 items stored in yourFirebase database, anChildAdded callback fires for each item.
As items change, you receiveChildAdded callbacks for items that enter thequery andChildRemoved 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:
FirebaseDatabase.DefaultInstance.GetReference("Leaders").OrderByChild("score").LimitToLast(1).ValueChanged+=HandleValueChanged;}voidHandleValueChanged(objectsender,ValueChangedEventArgsargs){if(args.DatabaseError!=null){Debug.LogError(args.DatabaseError.Message);return;}// Do something with the data in args.Snapshot}
Filter by key or value
You can useStartAt(),EndAt(), andEqualTo()to choose arbitrary starting, ending, and equivalence points for queries.This can be useful for paginating data or finding items with children that havea 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 is ordered as follows:
- Children with a
nullvalue for the specified child key come first. - Children with a value of
falsefor the specified child key come next. If multiple children have a value offalse, they are sortedlexicographically by key. - Children with a value of
truefor the specified child key come next. If multiple children have a value oftrue, they are sorted lexicographically by key. - 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.
- 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.
- Objects come last and are sorted lexicographically by key in ascending order.
OrderByKey
When usingOrderByKey()to sort your data, data is returned in ascending order by key.
- Children with a key that can be parsed as a 32-bit integer come first, sorted in ascending order.
- 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 ordering criteria are the same as inOrderByChild(), except the value of the node is used instead of the value of aspecified child key.
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 2026-02-18 UTC.