๐ 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
_idfield 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 onlytitleandauthorsshould be returned, and_idshould 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
titleandtotalInventoryfields.
Challengeโ
๐ 1. Retrieve only the title field for all books.โ
Answer
- JavaScript
- mongosh
- C#
const cursor = await books.find({}).project( {title: 1, _id: 0} ).limit(10);
await cursor.forEach((b) => {
console.log(b);
});
db.books.find({}, {title: 1, _id: 0});
var projection = Builders<Book>.Projection.Include(b => b.Title).Exclude(b => b.Id);
var booksWithOnlyTitle = booksCollection.Find(b => true).Project<Book>(projection).Limit(50).ToList();
if (booksWithOnlyTitle != null)
{
foreach (var book in booksWithOnlyTitle)
{
Console.WriteLine(book.ToJson()); // Shows the entire BSON document as JSON to show that some fields are null because they are not returned due to the projection
}
}
else
{
Console.WriteLine("Empty Collection");
}
๐ 2. Retrieve all fields except _id and authors for books in the "History" genre.โ
Answer
- JavaScript
- mongosh
- C#
const cursor = await books.find({ "genres": "History" }).project( { _id: 0, authors: 0 } ).limit(10);
await cursor.forEach((b) => {
console.log(b);
});
db.books.find({ "genres": "History" }, { _id: 0, authors: 0 });
var historyGenre = Builders<Book>.Filter.AnyEq(b => b.Genres, "History");
var projection = Builders<Book>.Projection.Exclude(b => b.Id).Exclude(b => b.Authors);
List<Book> sortedBooks = booksCollection.Find(historyGenre)
.Project<Book>(projection).Limit(50).ToList();
if (sortedBooks != null)
{
foreach (var book in sortedBooks)
{
Console.WriteLine(book.ToJson()); // Shows the entire BSON document as JSON to show that some fields are null because they are not returned due to the projection
}
}
else
{
Console.WriteLine("Empty Collection");
}