Skip to main content

๐Ÿ‘ SELECT โ†’ projection

In SQL, the SELECT statement allows us to specify which columns to retrieve from a table. Similarly, in MongoDB, we use projection in the .find() method to control which fields to include (or exclude) in query results.

Syntaxโ€‹

db.collection.find({ <query> }, { <projection> });

Projection basicsโ€‹

  • By default, MongoDB returns all fields in a document.
  • Use projection to include (1) or exclude (0) specific fields.
  • The _id field is always included unless explicitly excluded. 1

Example 1: Retrieve only title and authors fieldsโ€‹

db.books.find({}, { title: 1, authors: 1, _id: 0 });

Equivalent SQL query:

SELECT title, authors FROM books;

Here:

  • {} means "match all documents."
  • { title: 1, authors: 1, _id: 0 } specifies that only title and authors should be returned, and _id should be excluded.

Example 2: Exclude the reviews fieldโ€‹

db.books.find({}, { reviews: 0 });

Equivalent SQL query:

SELECT title, authors, genres, totalInventory, available FROM books;

Here:

  • We are removing reviews, but all other fields will still appear.

Example 3: Using projection along with a queryโ€‹

db.books.find({ genres: "Science" }, { title: 1, totalInventory: 1, _id: 0 });

Equivalent SQL query:

SELECT title, totalInventory FROM books WHERE genres='Science';

Here:

  • We first filter books that belong to the "Science" genre.
  • We then select only the title and totalInventory fields.

Challengeโ€‹

๐Ÿ‘ 1. Retrieve only the title field for all books.โ€‹

Answer
  db.books.find({}, {title: 1, _id: 0});

๐Ÿ‘ 2. Retrieve all fields except _id and authors for books in the "History" genre.โ€‹

Answer
  db.books.find({genres: "History"}, {_id: 0, authors: 0});