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
MongoDB aggregation and projection?
MongoDB aggregation with projection allows you to transform and reshape documents by selecting specific fields, computing new values, and controlling the output structure. The $project stage in the aggregation pipeline passes documents with requested fields to the next stage.
Syntax
db.collection.aggregate([
{ $project: {
field1: 1, // Include field
field2: 0, // Exclude field
newField: "$existingField", // Rename field
computedField: { $operation: "expression" }
}}
]);
Sample Data
Let us create a collection with documents ?
db.demo762.insertOne({
"_id": {
"userId": 101,
"userName": "Chris"
},
"countryName": "US",
"details": [
{
"Name": "Robert",
"DueDate": "2020-04-10"
},
{
"Name": "Robert",
"DueDate": "2020-04-09"
},
{
"Name": "Robert",
"DueDate": "2020-03-06"
}
]
});
{
"acknowledged": true,
"insertedId": {
"userId": 101,
"userName": "Chris"
}
}
Display all documents from the collection ?
db.demo762.find();
{
"_id": { "userId": 101, "userName": "Chris" },
"countryName": "US",
"details": [
{ "Name": "Robert", "DueDate": "2020-04-10" },
{ "Name": "Robert", "DueDate": "2020-04-09" },
{ "Name": "Robert", "DueDate": "2020-03-06" }
]
}
Example: Aggregation with Projection
The following query sorts details by DueDate and projects only the first 2 elements ?
db.demo762.aggregate([
{ "$match": {
"_id": { "$eq": { userId: 101, userName: "Chris" }}
}},
{ "$unwind": "$details" },
{ "$sort": { "details.DueDate": 1 }},
{ "$group": {
"_id": "$_id",
"details": { "$push": "$details" },
"countryName": { "$first": "$countryName" }
}},
{ "$project": {
"details": { "$slice": ["$details", 2] },
"countryName": 1
}}
]).pretty();
{
"_id": {
"userId": 101,
"userName": "Chris"
},
"countryName": "US",
"details": [
{
"Name": "Robert",
"DueDate": "2020-03-06"
},
{
"Name": "Robert",
"DueDate": "2020-04-09"
}
]
}
How It Works
-
$matchfilters documents by the specified criteria -
$unwinddeconstructs the details array into separate documents -
$sortorders documents by DueDate in ascending order -
$groupreassembles the array and preserves other fields -
$projectlimits the details array to first 2 elements using$slice
Conclusion
The $project stage in MongoDB aggregation enables field selection, transformation, and computed fields. Combined with other pipeline stages, it provides powerful document reshaping capabilities for complex data processing needs.
Advertisements
