Work with Lists of Data on the Web

Get a database reference

To read or write data from the database, you need an instance offirebase.database.Reference:

Web

import{getDatabase}from"firebase/database";constdatabase=getDatabase();

Web

vardatabase=firebase.database();
Note: By default, read and write access to your database is restricted so onlyauthenticated users can read or write data. To get started without setting upAuthentication, you canconfigure your rules for public access. This doesmake your database open to anyone, even people not using your app, so be sureto restrict your database again when you set up authentication.

Reading and writing lists

Append to a list of data

Use thepush() method to append data to a list in multiuser applications.Thepush() method generates a unique key every time a new child is added tothe specified Firebase reference. By using these auto-generated keys for eachnew element in the list, several clients can add children to the same locationat the same time without write conflicts. The unique key generated bypush()is based on a timestamp, so list items are automatically orderedchronologically.

You can use the reference to the new data returned by thepush() method to getthe value of the child's auto-generated key or set data for the child. The.key property of apush() reference contains the auto-generated key.

You can use these auto-generated keys to simplify flattening your datastructure. For more information, see the data fan-outexample.

For example,push() could be used to add a new post to a list of postsin a social application:

Web

import{getDatabase,ref,push,set}from"firebase/database";// Create a new post reference with an auto-generated idconstdb=getDatabase();constpostListRef=ref(db,'posts');constnewPostRef=push(postListRef);set(newPostRef,{// ...});

Web

// Create a new post reference with an auto-generated idvarpostListRef=firebase.database().ref('posts');varnewPostRef=postListRef.push();newPostRef.set({// ...});

Listen for child events

Child events are triggered in response to specific operations that happen tothe children of a node from an operation such as a new child added through thepush() method or a child being updated through theupdate() method.

EventTypical usage
child_added Retrieve lists of items or listen for additions to a list of items. This event is triggered once for each existing child and then again every time a new child is added to the specified path. The listener is passed a snapshot containing the new child's data.
child_changed Listen for changes to the items in a list. This event is triggered any time a child node is modified. This includes any modifications to descendants of the child node. The snapshot passed to the event listener contains the updated data for the child.
child_removed Listen for items being removed from a list. This event is triggered when an immediate child is removed.The snapshot passed to the callback block contains the data for the removed child.
child_moved Listen for changes to the order of items in an ordered list.child_moved events always follow thechild_changed event that caused the item's order to change (based on your current order-by method).

Each of these together can be useful for listening to changes to a specificnode in a database. For example, a social blogging app might use these methodstogether to monitor activity in the comments of a post, as shown below:

Web

import{getDatabase,ref,onChildAdded,onChildChanged,onChildRemoved}from"firebase/database";constdb=getDatabase();constcommentsRef=ref(db,'post-comments/'+postId);onChildAdded(commentsRef,(data)=>{addCommentElement(postElement,data.key,data.val().text,data.val().author);});onChildChanged(commentsRef,(data)=>{setCommentValues(postElement,data.key,data.val().text,data.val().author);});onChildRemoved(commentsRef,(data)=>{deleteComment(postElement,data.key);});

Web

varcommentsRef=firebase.database().ref('post-comments/'+postId);commentsRef.on('child_added',(data)=>{addCommentElement(postElement,data.key,data.val().text,data.val().author);});commentsRef.on('child_changed',(data)=>{setCommentValues(postElement,data.key,data.val().text,data.val().author);});commentsRef.on('child_removed',(data)=>{deleteComment(postElement,data.key);});

Listen for value events

While listening for child events is the recommended way to read lists of data,there are situations listening for value events on a list reference is useful.

Attaching avalue observer to a list of data will return theentire list of data as a single snapshot which you can then loop over toaccess individual children.

Even when there is only a single match for the query, the snapshot is still alist; it just contains a single item. To access the item, you need to loopover the result:

Web

import{getDatabase,ref,onValue}from"firebase/database";constdb=getDatabase();constdbRef=ref(db,'/a/b/c');onValue(dbRef,(snapshot)=>{snapshot.forEach((childSnapshot)=>{constchildKey=childSnapshot.key;constchildData=childSnapshot.val();// ...});},{onlyOnce:true});

Web

ref.once('value',(snapshot)=>{snapshot.forEach((childSnapshot)=>{varchildKey=childSnapshot.key;varchildData=childSnapshot.val();// ...});});

This pattern can be useful when you want to fetch all children of a listin a single operation, rather than listening for additional child addedevents.

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 or nested child path.
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 retrieve a list of a user'stop posts sorted by their star count:

Web

import{getDatabase,ref,query,orderByChild}from"firebase/database";import{getAuth}from"firebase/auth";constdb=getDatabase();constauth=getAuth();constmyUserId=auth.currentUser.uid;consttopUserPostsRef=query(ref(db,'user-posts/'+myUserId),orderByChild('starCount'));

Web

varmyUserId=firebase.auth().currentUser.uid;vartopUserPostsRef=firebase.database().ref('user-posts/'+myUserId).orderByChild('starCount');

This defines a query that when combined with achild listenersynchronizes the client with the user's posts from the path in the databasebased on their user ID, ordered by the number of stars each post has received.This technique of using IDs as index keys is called data fan out, you can readmore about it inStructure Your Database.

The call to theorderByChild() method specifies the child key to order theresults by. In this case, posts are sorted by the value of theirrespective"starCount" child. Queries can also be ordered by nestedchildren, in case you have data that looks like this:

"posts": {  "ts-functions": {    "metrics": {      "views" : 1200000,      "likes" : 251000,      "shares": 1200,    },    "title" : "Why you should use TypeScript for writing Cloud Functions",    "author": "Doug",  },  "android-arch-3": {    "metrics": {      "views" : 900000,      "likes" : 117000,      "shares": 144,    },    "title" : "Using Android Architecture Components with Firebase Realtime Database (Part 3)",    "author": "Doug",  }},

In this case, we can order our list elements by values nested under themetrics key by specifying the relative path to the nested child in ourorderByChild() call.

Web

import{getDatabase,ref,query,orderByChild}from"firebase/database";constdb=getDatabase();constmostViewedPosts=query(ref(db,'posts'),orderByChild('metrics/views'));

Web

varmostViewedPosts=firebase.database().ref('posts').orderByChild('metrics/views');

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.
startAfter()Return items greater than 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.
endBefore()Return items less than 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.

Limit the number of results

You can use thelimitToFirst() andlimitToLast() methods to set amaximum number of children to be synced for a given event. For example, ifyou uselimitToFirst() to set a limit of 100, you initially only receive upto 100child_added events. If you have fewer than 100 items stored in yourFirebase database, achild_added event fires for each item.

As items change, you receivechild_added events for items that enter thequery andchild_removed events for items that drop out of it so thatthe total number stays at 100.

The following example demonstrates how example blogging app defines a query toretrieve a list of the 100 most recent posts by all users:

Web

import{getDatabase,ref,query,limitToLast}from"firebase/database";constdb=getDatabase();constrecentPostsRef=query(ref(db,'posts'),limitToLast(100));

Web

varrecentPostsRef=firebase.database().ref('posts').limitToLast(100);

This example only defines a query, to actually synchronize data it needs tohave an attachedlistener.

Filter by key or value

You can usestartAt(),startAfter(),endAt(),endBefore(), andequalTo() to choose arbitrary starting, ending, and equivalence points forqueries. This can be useful for paginating data or finding items with childrenthat 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.

Detach listeners

Callbacks are removed by calling theoff() method on yourFirebase database reference.

You can remove a single listener by passing it as a parameter tooff().Callingoff() on the location with no arguments removes all listeners at thatlocation.

Callingoff() on a parent listener does notautomatically remove listeners registered on its child nodes;off() must also be called on any child listenersto remove the callback.

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-16 UTC.