0Pricing
MongoDB Academy · Lesson

Projection Best Practices for API Responses

Learners will design projections that align with REST API response shapes, reducing payload size and protecting sensitive fields.

Align Projections With API Response Shapes

Every REST or GraphQL endpoint your application exposes has a defined response shape. The ideal MongoDB projection returns exactly the fields that shape requires—no more, no less. When your projection mirrors your API response contract, you avoid two common anti-patterns: over-fetching (returning fields the endpoint never sends) and under-fetching (returning fields that force a second query).

Define Projection Constants

Hardcoding projection objects inline in every query leads to duplication and drift over time. Define projection constants alongside your data access functions or repositories. If the API response shape changes, you update one constant rather than hunting for every query in the codebase.

// projections.js — centralised projection definitions
export const USER_PUBLIC = { _id: 0, username: 1, avatarUrl: 1, createdAt: 1 };
export const USER_PROFILE = { _id: 0, username: 1, email: 1, bio: 1, avatarUrl: 1 };
export const USER_ADMIN = { _id: 0, username: 1, email: 1, role: 1, lastLoginAt: 1, isActive: 1 };

// Usage
const user = await db.collection('users').findOne({ username: 'alice' }, { projection: USER_PROFILE });

All lessons in this course

  1. Inclusion vs Exclusion Projections
  2. Projecting Nested and Array Fields
  3. The $ and $elemMatch Array Projections
  4. Projection Best Practices for API Responses
← Back to MongoDB Academy