0
0
GcpHow-ToBeginner · 3 min read

How to Use Limit in Firestore Queries

Use the limit(n) method in Firestore queries to restrict the number of documents returned to n. This helps control data size and improve performance by fetching only the needed documents.
📐

Syntax

The limit(n) method is added to a Firestore query to specify the maximum number of documents to return. Here, n is a positive integer representing the limit.

  • collection(): Selects the collection to query.
  • where(): (Optional) Filters documents by a condition.
  • limit(n): Limits the number of documents returned to n.
  • get(): Executes the query and fetches the documents.
javascript
db.collection('users').limit(5).get()
💻

Example

This example fetches up to 3 user documents from the 'users' collection and logs their names. It shows how to use limit() to control query size.

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

const firebaseConfig = {
  // your config here
};

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

async function fetchLimitedUsers() {
  const usersRef = collection(db, 'users');
  const q = query(usersRef, limit(3));
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((doc) => {
    console.log(doc.id, '=>', doc.data().name);
  });
}

fetchLimitedUsers();
Output
user1 => Alice user2 => Bob user3 => Carol
⚠️

Common Pitfalls

Common mistakes when using limit() include:

  • Not chaining limit() with a query, causing it to be ignored.
  • Using limit() without an order, which may return unpredictable documents.
  • Expecting limit() to paginate results without using cursors.

Always combine limit() with orderBy() for consistent results and use cursors for pagination.

javascript
// Incorrect usage:
// const qWrong = collection(db, 'users').limit(3); // This is invalid because limit() is not a method on collection reference

// Correct usage:
import { orderBy } from 'firebase/firestore';
const qRight = query(collection(db, 'users'), orderBy('name'), limit(3));
📊

Quick Reference

MethodDescription
collection('name')Selects the collection to query
where(field, op, value)Filters documents by condition
orderBy(field)Sorts documents by a field
limit(n)Limits the number of documents returned to n
get()Executes the query and fetches documents

Key Takeaways

Use limit(n) to restrict the number of documents returned by a Firestore query.
Always combine limit() with orderBy() for predictable results.
Use query() to chain limit() properly in Firestore SDK v9+.
limit() alone does not paginate; use cursors for pagination.
Fetching fewer documents improves app performance and reduces costs.