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
Project field in MongoDB
To project field in MongoDB, use $project in an aggregation pipeline. The $project stage allows you to reshape documents by including, excluding, or creating new fields.
Syntax
db.collection.aggregate([
{
$project: {
"fieldName": 1, // Include field
"newField": "$existingField", // Rename field
"_id": 0 // Exclude _id
}
}
]);
Sample Data
db.demo439.insertMany([
{
"Name": "Chris",
"MarksInformation": {
"Marks1": 67,
"Marks2": 45,
"Marks3": 78
}
},
{
"Name": "David",
"MarksInformation": {
"Marks1": 50,
"Marks2": 57,
"Marks3": 68
}
},
{
"Name": "Bob",
"MarksInformation": {
"Score1": 65,
"Score2": 71
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e77833abbc41e36cc3caeab"),
ObjectId("5e77833abbc41e36cc3caeac"),
ObjectId("5e77833bbbc41e36cc3caead")
]
}
Display All Documents
db.demo439.find();
{ "_id" : ObjectId("5e77833abbc41e36cc3caeab"), "Name" : "Chris", "MarksInformation" : { "Marks1" : 67, "Marks2" : 45, "Marks3" : 78 } }
{ "_id" : ObjectId("5e77833abbc41e36cc3caeac"), "Name" : "David", "MarksInformation" : { "Marks1" : 50, "Marks2" : 57, "Marks3" : 68 } }
{ "_id" : ObjectId("5e77833bbbc41e36cc3caead"), "Name" : "Bob", "MarksInformation" : { "Score1" : 65, "Score2" : 71 } }
Example: Project Fields with Conditional Logic
This query normalizes different field names (Marks vs Score) into a consistent output ?
db.demo439.aggregate([
{
$project: {
"Name": 1,
"Marks1": {
$cond: [
{ $eq: [{ $ifNull: ["$MarksInformation.Marks1", 0] }, 0] },
{ $ifNull: ["$MarksInformation.Score1", 0] },
"$MarksInformation.Marks1"
]
},
"Marks2": {
$cond: [
{ $eq: [{ $ifNull: ["$MarksInformation.Marks2", 0] }, 0] },
{ $ifNull: ["$MarksInformation.Score2", 0] },
"$MarksInformation.Marks2"
]
},
"Marks3": {
$cond: [
{ $eq: [{ $ifNull: ["$MarksInformation.Marks3", 0] }, 0] },
{ $ifNull: ["$MarksInformation.Score3", 0] },
"$MarksInformation.Marks3"
]
}
}
}
]);
{ "_id" : ObjectId("5e77833abbc41e36cc3caeab"), "Name" : "Chris", "Marks1" : 67, "Marks2" : 45, "Marks3" : 78 }
{ "_id" : ObjectId("5e77833abbc41e36cc3caeac"), "Name" : "David", "Marks1" : 50, "Marks2" : 57, "Marks3" : 68 }
{ "_id" : ObjectId("5e77833bbbc41e36cc3caead"), "Name" : "Bob", "Marks1" : 65, "Marks2" : 71, "Marks3" : 0 }
How It Works
-
$condperforms conditional logic (if-else) -
$ifNullreturns a default value when a field is null or missing -
$eqchecks if values are equal - The query checks if "Marks" fields exist; if not, it uses "Score" fields instead
Conclusion
The $project stage in MongoDB's aggregation pipeline allows you to reshape documents by selecting, renaming, and creating fields. Combined with conditional operators like $cond, you can normalize data with different field structures.
Advertisements
