Skip to main content

πŸ‘ $match and $project

MongoDB’s Aggregation Framework allows for powerful data transformations and analysis. The $match, $project, and $sort stages are fundamental building blocks of an aggregation pipeline.


πŸ”Ή $match β†’ Filtering data​

Just like .find() based on the query mentioned, the $match stage filters documents from the collection.

Syntax​

{ $match: { <query> } }

Example: Get all the books that were published after the year 2010​

db.books.aggregate([
{
$match: { year: { $gt: 2010 } },
},
]);
info

Place $match as early as possible in the pipeline to reduce the number of documents processed in later stages.


πŸ”Ή $project β†’ Selecting fields​

  • The $project stage controls which fields are included in the output.
  • It can also be used for adding computed fields to the results.

Syntax​

{
$project: {
field1: 1,
field2: 1,
_id: 0
}
}
  • 1: Include the field
  • 0: Exclude the field

Example: Get all the books published after the year 2010. The output should only include the title, year, and page count of the book.​

db.books.aggregate([
{
$match: { year: { $gt: 2010 } },
},
{
$project: {
title: 1,
year: 1,
pages: 1,
_id: 0,
},
},
]);

Equivalent SQL query​

SELECT title, year, pages FROM books WHERE year>2010;

Computed fields example: Along with the title and authors, also output the count of authors for every book in the database.​

db.books.aggregate([
{
$project: {
title: 1,
authors: 1,
authorCount: { $size: "$authors" },
},
},
]);

Challenge πŸš€β€‹

πŸ‘ 1. Find books with more than 2 available copies.​

Answer
  db.books.aggregate([
{ $match: {available: {$gt: 2}}}
]);

πŸ‘ 2. Find books with more than 2 available copies. Return only book titles and publication year.​

Answer
  db.books.aggregate([
{ $match: {available: {$gt: 2}}},
{ $project: {title: 1, year: 1, _id: 0}}
]);