0
0
FirebaseHow-ToBeginner · 3 min read

How to Use orderBy in Firestore for Sorted Queries

Use orderBy in Firestore queries to sort documents by a specific field in ascending or descending order. Chain orderBy after your collection reference and before get() or onSnapshot() to apply sorting.
📐

Syntax

The orderBy method sorts documents by a field. It takes two arguments: the field name (string) and an optional direction ('asc' for ascending or 'desc' for descending). If direction is omitted, it defaults to ascending.

  • collectionRef.orderBy(field, direction)
  • field: The document field to sort by.
  • direction: Optional, 'asc' or 'desc'.
javascript
collectionRef.orderBy('fieldName', 'asc')
💻

Example

This example shows how to get all documents from the 'users' collection sorted by the 'age' field in ascending order.

javascript
import { getFirestore, collection, query, orderBy, getDocs } from 'firebase/firestore';

const db = getFirestore();
const usersRef = collection(db, 'users');
const q = query(usersRef, orderBy('age', 'asc'));

async function getSortedUsers() {
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((doc) => {
    console.log(doc.id, '=>', doc.data());
  });
}

getSortedUsers();
Output
user1 => { name: 'Alice', age: 22 } user3 => { name: 'Bob', age: 25 } user2 => { name: 'Carol', age: 30 }
⚠️

Common Pitfalls

Common mistakes when using orderBy include:

  • Not creating an index for the ordered field, causing Firestore errors.
  • Using orderBy on a field that does not exist in some documents.
  • Mixing orderBy with where filters on different fields without proper composite indexes.
  • Forgetting to specify direction when descending order is needed.
javascript
/* Wrong: Missing index error if no index exists for 'score' */
const qWrong = query(collection(db, 'games'), orderBy('score', 'desc'));

/* Right: Create index in Firestore console or follow error link to create it */
const qRight = query(collection(db, 'games'), orderBy('score', 'desc'));
📊

Quick Reference

MethodDescriptionExample
orderBy(field)Sorts by field ascending (default)orderBy('name')
orderBy(field, 'asc')Sorts by field ascendingorderBy('age', 'asc')
orderBy(field, 'desc')Sorts by field descendingorderBy('score', 'desc')

Key Takeaways

Use orderBy to sort Firestore query results by a specific field.
Specify 'asc' or 'desc' to control sort direction; default is ascending.
Ensure Firestore indexes exist for fields used in orderBy to avoid errors.
Combine orderBy with where filters carefully, respecting index requirements.
orderBy must be chained before executing the query with getDocs or onSnapshot.