Skip to content

Instantly share code, notes, and snippets.

@powertech2nd
Created March 5, 2026 11:46
Show Gist options
  • Select an option

  • Save powertech2nd/114ea8f88d6ea9dc3a2158b434abdffe to your computer and use it in GitHub Desktop.

Select an option

Save powertech2nd/114ea8f88d6ea9dc3a2158b434abdffe to your computer and use it in GitHub Desktop.

03 — Projections (Selecting Specific Columns)

Goal: Return only the fields you need, not the entire document. Key Idea: In MongoDB, .find() takes two arguments — the filter, then the projection.


The Two-Argument Pattern

db.collection.find(
  { /* filter  — like WHERE  */ },
  { /* projection — like SELECT */ }
);

Projection Values

Value Meaning
1 Include this field
0 Exclude this field

Rule: You can either include fields (1) or exclude fields (0) — generally not both in the same projection (except for _id).


Task: Get only username and email for active users

SQL Way

SELECT username, email
FROM Users
WHERE status = 'active';

MongoDB Way

db.users.find(
  { status: "active" },              // Stage 1: Filter  (WHERE)
  { username: 1, email: 1, _id: 0 } // Stage 2: Projection (SELECT)
);

🔍 Breaking It Down

{ username: 1, email: 1, _id: 0 }
//           ↑           ↑
//     include       exclude _id
//
// By default, _id is ALWAYS included.
// You must explicitly set _id: 0 to hide it.

More Examples

Show all fields EXCEPT one (exclusion projection)

// Hide the password field, show everything else
db.users.find(
  { status: "active" },
  { password: 0 }
);

Get only the name (inclusion projection)

db.users.find(
  {},           // No filter = match all documents
  { name: 1, _id: 0 }
);

💡 Notes

  • _id is the only field you can mix with an inclusion projection (e.g., { name: 1, _id: 0 }).
  • Mixing 0 and 1 for other fields in the same projection will throw an error.
  • An empty filter {} means "match everything" — like SELECT with no WHERE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment