0
0
GcpHow-ToBeginner · 3 min read

How to Use orderBy in Firestore for Sorted Queries

Use the orderBy method on a Firestore query to sort documents by a field in ascending or descending order. Chain orderBy after collection or where to specify the sorting field and direction.
📐

Syntax

The orderBy method sorts query results by a specified field. It takes two arguments: the field name as a string, and an optional direction which can be asc for ascending or desc for descending order. If direction is omitted, ascending order is used by default.

javascript
db.collection('collectionName').orderBy('fieldName', 'asc')
💻

Example

This example shows how to get documents from a Firestore collection named users sorted by the age field in descending order.

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

const firebaseConfig = {
  // your config here
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

async function getUsersSortedByAge() {
  const usersRef = collection(db, 'users');
  const q = query(usersRef, orderBy('age', 'desc'));
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((doc) => {
    console.log(doc.id, '=>', doc.data());
  });
}

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

Common Pitfalls

  • Trying to order by a field not indexed will cause an error; Firestore requires indexes for ordered queries.
  • Mixing orderBy with where filters on different fields may require composite indexes.
  • Using orderBy on a field that sometimes is missing in documents can lead to unexpected order.
javascript
/* Wrong: ordering by a field without index */
db.collection('users').orderBy('nonIndexedField')

/* Right: create index in Firestore console or use indexed field */
db.collection('users').orderBy('age')
📊

Quick Reference

Remember these tips when using orderBy:

  • Default order is ascending.
  • Use 'desc' for descending order.
  • Combine multiple orderBy calls to sort by multiple fields.
  • Ensure proper indexes exist for your queries.

Key Takeaways

Use orderBy to sort Firestore query results by a specific field in ascending or descending order.
Always ensure the field you order by is indexed to avoid query errors.
You can chain multiple orderBy calls to sort by more than one field.
The default sort direction is ascending if not specified.
Combining orderBy with where filters may require composite indexes.