π $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 field0
: 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}}
]);