AQuery sorts and filters the data at a Database location so only a subsetof the child data is included. This can be used to order a collection ofdata by some attribute (for example, height of dinosaurs) as well as torestrict a large list of items (for example, chat messages) down to a numbersuitable for synchronizing to the client. Queries are created by chainingtogether one or more of the filter methods defined here.

Just as with aReference, you can receive data from aQuery by using theon() method. You will only receive events andDataSnapshots for thesubset of the data that matches your query.

Read our documentation on Sorting and filtering data for more information.

Index

Properties

ref

Returns aReference to theQuery's location.

Methods

endAt

  • endAt(valuenumber |string |boolean |null, key?: string):Query
  • Creates aQuery with the specified ending point.

    UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo()allows you to choose arbitrary starting and ending points for your queries.

    The ending point is inclusive, so children with exactly the specified valuewill be included in the query. The optional key argument can be used tofurther limit the range of the query. If it is specified, then children thathave exactly the specified value must also have a key name less than or equalto the specified key.

    You can read more aboutendAt() in Filtering data.

    example
    // Find all dinosaurs whose names come before Pterodactyl lexicographically.// Include Pterodactyl in the result.var ref = firebase.database().ref("dinosaurs");ref.orderByKey().endAt("pterodactyl").on("child_added",function(snapshot){console.log(snapshot.key);});

    Parameters

    • value:number |string |boolean |null

      The value to end at. The argumenttype depends on whichorderBy*() function was used in this query.Specify a value that matches theorderBy*() type. When used incombination withorderByKey(), the value must be a string.

    • Optional key:string

      The child key to end at, among the children with thepreviously specified priority. This argument is only allowed if ordering bychild, value, or priority.

    ReturnsQuery

endBefore

  • endBefore(valuenumber |string |boolean |null, key?: string):Query
  • Creates aQuery with the specified ending point (exclusive).

    UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo()allows you to choose arbitrary starting and ending points for your queries.

    The ending point is exclusive. If only a value is provided, childrenwith a value less than the specified value will be included in the query.If a key is specified, then children must have a value lesss than or equalto the specified value and a a key name less than the specified key.

    example
    // Find all dinosaurs whose names come before Pterodactyl lexicographically.// Do not include Pterodactyl in the result.var ref = firebase.database().ref("dinosaurs");ref.orderByKey().endBefore("pterodactyl").on("child_added",function(snapshot){console.log(snapshot.key);});@param value The value to end before. The argument  type depends on which`orderBy*()`functionwasusedinthisquery.Specifyavaluethatmatchesthe `orderBy*()`type.Whenusedincombinationwith `orderByKey()`,thevaluemustbeastring.@paramkeyThechildkeytoendbefore,amongthechildrenwiththepreviouslyspecifiedpriority.Thisargumentisonlyallowediforderingbychild,value,orpriority.

    Parameters

    • value:number |string |boolean |null
    • Optional key:string

    ReturnsQuery

equalTo

  • equalTo(valuenumber |string |boolean |null, key?: string):Query
  • Creates aQuery that includes children that match the specified value.

    UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo()allows you to choose arbitrary starting and ending points for your queries.

    The optional key argument can be used to further limit the range of thequery. If it is specified, then children that have exactly the specifiedvalue must also have exactly the specified key as their key name. This can beused to filter result sets with many matches for the same value.

    You can read more aboutequalTo() in Filtering data.

    example
    // Find all dinosaurs whose height is exactly 25 meters.var ref = firebase.database().ref("dinosaurs");ref.orderByChild("height").equalTo(25).on("child_added",function(snapshot){console.log(snapshot.key);});

    Parameters

    • value:number |string |boolean |null

      The value to match for. Theargument type depends on whichorderBy*() function was used in thisquery. Specify a value that matches theorderBy*() type. When used incombination withorderByKey(), the value must be a string.

    • Optional key:string

      The child key to start at, among the children with thepreviously specified priority. This argument is only allowed if ordering bychild, value, or priority.

    ReturnsQuery

get

  • get():Promise<DataSnapshot>
  • Gets the most up-to-date result for this query.

    ReturnsPromise<DataSnapshot>

    A promise which resolves to the resulting DataSnapshot ifa value is available, or rejects if the client is unable to returna value (e.g., if the server is unreachable and there is nothingcached).

isEqual

  • isEqual(otherQuery |null):boolean
  • Returns whether or not the current and provided queries represent the samelocation, have the same query parameters, and are from the same instance offirebase.app.App.

    TwoReference objects are equivalent if they represent the same locationand are from the same instance offirebase.app.App.

    TwoQuery objects are equivalent if they represent the same location, havethe same query parameters, and are from the same instance offirebase.app.App. Equivalent queries share the same sort order, limits, andstarting and ending points.

    example
    var rootRef = firebase.database.ref();var usersRef = rootRef.child("users");usersRef.isEqual(rootRef);// falseusersRef.isEqual(rootRef.child("users"));// trueusersRef.parent.isEqual(rootRef);// true
    example
    var rootRef = firebase.database.ref();var usersRef = rootRef.child("users");var usersQuery = usersRef.limitToLast(10);usersQuery.isEqual(usersRef);// falseusersQuery.isEqual(usersRef.limitToLast(10));// trueusersQuery.isEqual(rootRef.limitToLast(10));// falseusersQuery.isEqual(usersRef.orderByKey().limitToLast(10));// false

    Parameters

    • other:Query |null

      The query to compare against.

    Returnsboolean

    Whether or not the current and provided queries areequivalent.

limitToFirst

  • limitToFirst(limitnumber):Query
  • Generates a newQuery limited to the first specific number of children.

    ThelimitToFirst() method is used to set a maximum number of children to besynced for a given callback. If we set a limit of 100, we will initially onlyreceive up to 100child_added events. If we have fewer than 100 messagesstored in our Database, achild_added event will fire for each message.However, if we have over 100 messages, we will only receive achild_addedevent for the first 100 ordered messages. As items change, we will receivechild_removed events for each item that drops out of the active list sothat the total number stays at 100.

    You can read more aboutlimitToFirst() in Filtering data.

    example
    // Find the two shortest dinosaurs.var ref = firebase.database().ref("dinosaurs");ref.orderByChild("height").limitToFirst(2).on("child_added",function(snapshot){// This will be called exactly two times (unless there are less than two// dinosaurs in the Database).// It will also get fired again if one of the first two dinosaurs is// removed from the data set, as a new dinosaur will now be the second// shortest.console.log(snapshot.key);});

    Parameters

    • limit:number

      The maximum number of nodes to include in this query.

    ReturnsQuery

limitToLast

  • limitToLast(limitnumber):Query
  • Generates a newQuery object limited to the last specific number ofchildren.

    ThelimitToLast() method is used to set a maximum number of children to besynced for a given callback. If we set a limit of 100, we will initially onlyreceive up to 100child_added events. If we have fewer than 100 messagesstored in our Database, achild_added event will fire for each message.However, if we have over 100 messages, we will only receive achild_addedevent for the last 100 ordered messages. As items change, we will receivechild_removed events for each item that drops out of the active list sothat the total number stays at 100.

    You can read more aboutlimitToLast() in Filtering data.

    example
    // Find the two heaviest dinosaurs.var ref = firebase.database().ref("dinosaurs");ref.orderByChild("weight").limitToLast(2).on("child_added",function(snapshot){// This callback will be triggered exactly two times, unless there are// fewer than two dinosaurs stored in the Database. It will also get fired// for every new, heavier dinosaur that gets added to the data set.console.log(snapshot.key);});

    Parameters

    • limit:number

      The maximum number of nodes to include in this query.

    ReturnsQuery

off

  • off(eventType?: EventType, callback?: (aDataSnapshot, b?: string |null) =>any, context?: Object |null):void
  • Detaches a callback previously attached withon().

    Detach a callback previously attached withon(). Note that ifon() wascalled multiple times with the same eventType and callback, the callbackwill be called multiple times for each event, andoff() must be calledmultiple times to remove the callback. Callingoff() on a parent listenerwill not automatically remove listeners registered on child nodes,off()must also be called on any child listeners to remove the callback.

    If a callback is not specified, all callbacks for the specified eventTypewill be removed. Similarly, if no eventType is specified, all callbacksfor theReference will be removed.

    example
    var onValueChange =function(dataSnapshot){  ... };ref.on('value', onValueChange);ref.child('meta-data').on('child_added', onChildAdded);// Sometime later...ref.off('value', onValueChange);// You must also call off() for any child listeners on ref// to cancel those callbacksref.child('meta-data').off('child_added', onValueAdded);
    example
    // Or you can save a line of code by using an inline function// and on()'s return value.var onValueChange = ref.on('value',function(dataSnapshot){ ... });// Sometime later...ref.off('value', onValueChange);

    Parameters

    • Optional eventType:EventType

      One of the following strings: "value","child_added", "child_changed", "child_removed", or "child_moved." Ifomitted, all callbacks for theReference will be removed.

    • Optional callback:(a:DataSnapshot, b?:string |null) =>any

      The callback function that was passed toon() orundefined to remove all callbacks.

    • Optional context:Object |null

      The context that was passed toon().

    Returnsvoid

on

  • on(eventTypeEventType, callback(aDataSnapshot, b?: string |null) =>any, cancelCallbackOrContext?: ((aError) =>any) |Object |null, context?: Object |null):(aDataSnapshot |null, b?: string |null) =>any
  • Listens for data changes at a particular location.

    This is the primary way to read data from a Database. Your callbackwill be triggered for the initial data and again whenever the data changes.Useoff( ) to stop receiving updates. See Retrieve Data on the Webfor more details.

    value event

    This event will trigger once with the initial data stored at this location,and then trigger again each time the data changes. TheDataSnapshot passedto the callback will be for the location at whichon() was called. Itwon't trigger until the entire contents has been synchronized. If thelocation has no data, it will be triggered with an emptyDataSnapshot(val() will returnnull).

    child_added event

    This event will be triggered once for each initial child at this location,and it will be triggered again every time a new child is added. TheDataSnapshot passed into the callback will reflect the data for therelevant child. For ordering purposes, it is passed a second argument whichis a string containing the key of the previous sibling child by sort order,ornull if it is the first child.

    child_removed event

    This event will be triggered once every time a child is removed. TheDataSnapshot passed into the callback will be the old data for the childthat was removed. A child will get removed when either:

    • a client explicitly callsremove() on that child or one of its ancestors
    • a client callsset(null) on that child or one of its ancestors
    • that child has all of its children removed
    • there is a query in effect which now filters out the child (because it'ssort order changed or the max limit was hit)

    child_changed event

    This event will be triggered when the data stored in a child (or any of itsdescendants) changes. Note that a singlechild_changed event may representmultiple changes to the child. TheDataSnapshot passed to the callback willcontain the new child contents. For ordering purposes, the callback is alsopassed a second argument which is a string containing the key of the previoussibling child by sort order, ornull if it is the first child.

    child_moved event

    This event will be triggered when a child's sort order changes such that itsposition relative to its siblings changes. TheDataSnapshot passed to thecallback will be for the data of the child that has moved. It is also passeda second argument which is a string containing the key of the previoussibling child by sort order, ornull if it is the first child.

    example

    Handle a new value:

    ref.on('value',function(dataSnapshot){  ...});
    example

    Handle a new child:

    ref.on('child_added',function(childSnapshot, prevChildKey){  ...});
    example

    Handle child removal:

    ref.on('child_removed',function(oldChildSnapshot){  ...});
    example

    Handle child data changes:

    ref.on('child_changed',function(childSnapshot, prevChildKey){  ...});
    example

    Handle child ordering changes:

    ref.on('child_moved',function(childSnapshot, prevChildKey){  ...});

    Parameters

    • eventType:EventType

      One of the following strings: "value","child_added", "child_changed", "child_removed", or "child_moved."

    • callback:(a:DataSnapshot, b?:string |null) =>any

      Acallback that fires when the specified event occurs. The callback will bepassed a DataSnapshot. For ordering purposes, "child_added","child_changed", and "child_moved" will also be passed a string containingthe key of the previous child, by sort order, ornull if it is thefirst child.

    • Optional cancelCallbackOrContext:((a:Error) =>any) |Object |null

      An optionalcallback that will be notified if your event subscription is ever canceledbecause your client does not have permission to read this data (or it hadpermission but has now lost it). This callback will be passed anErrorobject indicating why the failure occurred.

    • Optional context:Object |null

      If provided, this object will be used asthiswhen calling your callback(s).

    Returns(a:DataSnapshot |null, b?:string |null) =>any

    The providedcallback function is returned unmodified. This is just for convenience ifyou want to pass an inline function toon() but store the callbackfunction for later passing tooff().

once

  • once(eventTypeEventType, successCallback?: (aDataSnapshot, b?: string |null) =>any, failureCallbackOrContext?: ((aError) =>void) |Object |null, context?: Object |null):Promise<DataSnapshot>
  • Listens for exactly one event of the specified event type, and then stopslistening.

    This is equivalent to callingon(), andthen callingoff() inside the callbackfunction. Seeon() for details on theevent types.

    example
    // Basic usage of .once() to read the data located at ref.ref.once('value')  .then(function(dataSnapshot){// handle read data.  });

    Parameters

    • eventType:EventType

      One of the following strings: "value","child_added", "child_changed", "child_removed", or "child_moved."

    • Optional successCallback:(a:DataSnapshot, b?:string |null) =>any

      Acallback that fires when the specified event occurs. The callback will bepassed a DataSnapshot. For ordering purposes, "child_added","child_changed", and "child_moved" will also be passed a string containingthe key of the previous child by sort order, ornull if it is thefirst child.

    • Optional failureCallbackOrContext:((a:Error) =>void) |Object |null

      An optionalcallback that will be notified if your client does not have permission toread the data. This callback will be passed anError object indicatingwhy the failure occurred.

    • Optional context:Object |null

      If provided, this object will be used asthiswhen calling your callback(s).

    ReturnsPromise<DataSnapshot>

orderByChild

  • orderByChild(pathstring):Query
  • Generates a newQuery object ordered by the specified child key.

    Queries can only order by one key at a time. CallingorderByChild()multiple times on the same query is an error.

    Firebase queries allow you to order your data by any child key on the fly.However, if you know in advance what your indexes will be, you can definethem via the .indexOn rule in your Security Rules for better performance. Seethe.indexOn rule for more information.

    You can read more aboutorderByChild() in Sort data.

    example
    var ref = firebase.database().ref("dinosaurs");ref.orderByChild("height").on("child_added",function(snapshot){console.log(snapshot.key +" was " + snapshot.val().height +" m tall");});

    Parameters

    • path:string

    ReturnsQuery

orderByKey

  • orderByKey():Query
  • Generates a newQuery object ordered by key.

    Sorts the results of a query by their (ascending) key values.

    You can read more aboutorderByKey() in Sort data.

    example
    var ref = firebase.database().ref("dinosaurs");ref.orderByKey().on("child_added",function(snapshot){console.log(snapshot.key);});

    ReturnsQuery

orderByPriority

  • orderByPriority():Query
  • Generates a newQuery object ordered by priority.

    Applications need not use priority but can order collections byordinary properties (see Sort data for alternatives to priority.

    ReturnsQuery

orderByValue

  • orderByValue():Query
  • Generates a newQuery object ordered by value.

    If the children of a query are all scalar values (string, number, orboolean), you can order the results by their (ascending) values.

    You can read more aboutorderByValue() in Sort data.

    example
    var scoresRef = firebase.database().ref("scores");scoresRef.orderByValue().limitToLast(3).on("value",function(snapshot){  snapshot.forEach(function(data){console.log("The " + data.key +" score is " + data.val());  });});

    ReturnsQuery

startAfter

  • startAfter(valuenumber |string |boolean |null, key?: string):Query
  • Creates aQuery with the specified starting point (exclusive).

    UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo()allows you to choose arbitrary starting and ending points for your queries.

    The starting point is exclusive. If only a value is provided, childrenwith a value greater than the specified value will be included in the query.If a key is specified, then children must have a value greater than or equalto the specified value and a a key name greater than the specified key.

    example
    // Find all dinosaurs that are more than three meters tall.var ref = firebase.database().ref("dinosaurs");ref.orderByChild("height").startAfter(3).on("child_added",function(snapshot){console.log(snapshot.key)});

    Parameters

    • value:number |string |boolean |null

      The value to start after. The argumenttype depends on whichorderBy*() function was used in this query.Specify a value that matches theorderBy*() type. When used incombination withorderByKey(), the value must be a string.

    • Optional key:string

      The child key to start after. This argument is only allowedif ordering by child, value, or priority.

    ReturnsQuery

startAt

  • startAt(valuenumber |string |boolean |null, key?: string):Query
  • Creates aQuery with the specified starting point.

    UsingstartAt(),startAfter(),endBefore(),endAt() andequalTo()allows you to choose arbitrary starting and ending points for your queries.

    The starting point is inclusive, so children with exactly the specified valuewill be included in the query. The optional key argument can be used tofurther limit the range of the query. If it is specified, then children thathave exactly the specified value must also have a key name greater than orequal to the specified key.

    You can read more aboutstartAt() in Filtering data.

    example
    // Find all dinosaurs that are at least three meters tall.var ref = firebase.database().ref("dinosaurs");ref.orderByChild("height").startAt(3).on("child_added",function(snapshot){console.log(snapshot.key)});

    Parameters

    • value:number |string |boolean |null

      The value to start at. The argumenttype depends on whichorderBy*() function was used in this query.Specify a value that matches theorderBy*() type. When used incombination withorderByKey(), the value must be a string.

    • Optional key:string

      The child key to start at. This argument is only allowedif ordering by child, value, or priority.

    ReturnsQuery

toJSON

  • toJSON():Object
  • Returns a JSON-serializable representation of this object.

    ReturnsObject

    A JSON-serializable representation of this object.

toString

  • toString():string
  • Gets the absolute URL for this location.

    ThetoString() method returns a URL that is ready to be put into a browser,curl command, or afirebase.database().refFromURL() call. Since all ofthose expect the URL to be url-encoded,toString() returns an encoded URL.

    Append '.json' to the returned URL when typed into a browser to downloadJSON-formatted data. If the location is secured (that is, not publiclyreadable), you will get a permission-denied error.

    example
    // Calling toString() on a root Firebase reference returns the URL where its// data is stored within the Database:var rootRef = firebase.database().ref();var rootUrl = rootRef.toString();// rootUrl === "https://sample-app.firebaseio.com/".// Calling toString() at a deeper Firebase reference returns the URL of that// deep path within the Database:var adaRef = rootRef.child('users/ada');var adaURL = adaRef.toString();// adaURL === "https://sample-app.firebaseio.com/users/ada".

    Returnsstring

    The absolute URL for this location.

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 2022-07-27 UTC.