Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Implement match and project in MongoDB aggregate
The $match operator filters documents to pass only those that match specified conditions to the next pipeline stage. The $project operator reshapes documents by including, excluding, or adding new fields before passing them to the next stage.
Syntax
db.collection.aggregate([
{ $match: { field: value } },
{ $project: { field1: 1, field2: 0, newField: "$existingField" } }
]);
Sample Data
Let us create a collection with student documents ?
db.demo545.insertMany([
{
"Name": "Chris",
"details": {
"SubjectScore1": 56,
"SubjectScore2": 56
}
},
{
"Name": "David",
"details": {
"SubjectScore1": 78,
"SubjectScore2": 78
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e8e246e9e5f92834d7f05d5"),
ObjectId("5e8e24709e5f92834d7f05d6")
]
}
Display all documents from the collection ?
db.demo545.find();
{
"_id": ObjectId("5e8e246e9e5f92834d7f05d5"),
"Name": "Chris",
"details": {
"SubjectScore1": 56,
"SubjectScore2": 56
}
}
{
"_id": ObjectId("5e8e24709e5f92834d7f05d6"),
"Name": "David",
"details": {
"SubjectScore1": 78,
"SubjectScore2": 78
}
}
Example: Combining $match, $project, and $group
Use aggregation to filter documents, project specific fields, and group by SubjectScore2 values ?
db.demo545.aggregate([
{ $match: {} },
{
$project: {
"_id": 0,
"details.SubjectScore1": 1,
"out": "$details.SubjectScore2"
}
},
{
$group: {
"_id": "$out"
}
}
]);
{ "_id": 78 }
{ "_id": 56 }
How It Works
-
$match: {}− Passes all documents (empty filter matches everything) -
$project− Excludes_id, includesSubjectScore1, creates new fieldoutwithSubjectScore2values -
$group− Groups documents by theoutfield values, creating unique score groups
Conclusion
Combine $match and $project in aggregation pipelines to filter and reshape data efficiently. The $match stage should typically come first to reduce the dataset size early in the pipeline.
Advertisements
