You're viewing the legacy docs. They are deprecated as of May 18, 2016.
These docs are for version 2.4.2 and below of the Javascript SDK. Go to our current docs, or see our Web migration guide.

Version 2.4.2Changelog

Query

A Query sorts and filters the data at a database location so only a subset of the child data is included. This can be used to order a collection of data by some attribute (e.g. height of dinosaurs) as well as to restrict a large list of items (e.g. chat messages) down to a number suitable for synchronizing to the client. Queries are created by chaining together one or more of the filter functions defined below.

Just like with a regular Firebase reference, we can receive data from a Query object by using the on() method. We will only receive events and DataSnapshots for the subset of the data that matches our query.

Read our documentation on ordering and querying data for more information.

Tutorial

Let's assume we are making a chat application which stores a bunch of messages in a /messages/ node within our database. Each message looks like this:

{
  "timestamp": 1414622353680,
  "uid": "user198",
  "text": "Realtime, baby!"
}

If we want to retrieve the 100 most recent messages in the conversation, we first need to sort the data by the timestamp key and then limit the query to 100 items. Once we have created a Query with the filtered data, we can listen for the child_added event for each matching message:

var ref = new Firebase("https://docs-examples.firebaseio.com/samplechat/messages");
var query = ref.orderByChild("timestamp").limitToLast(100);
query.on("child_added", function(messageSnapshot) {
  // This will only be called for the last 100 messages
  var messageData = messageSnapshot.val();
});

The child_added event will initially fire 100 times. The callback will also fire for every new message added to the query. When this happens, we will also see child_removed events fire for those messages which have fallen out of the sliding query window. We can listen for those events as well:

query.on("child_removed", function(removedMessageSnapshot) {
  // A child was pushed out of the query and is therefore showing up as removed
  var removedMessageData = removedMessageSnapshot.val();
});

This is just a small sample of what can be done with Firebase queries. Read our documentation on ordering and querying data for more information and examples.