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
Creating alias in a MongoDB query?
To create an alias in a MongoDB query, use the aggregation framework with the $project stage. This allows you to rename fields in the output by mapping original field names to new alias names.
Syntax
db.collection.aggregate([
{
$project: {
_id: 1,
"aliasName": "$originalFieldName"
}
}
]);
Sample Data
db.creatingAliasDemo.insertMany([
{_id: 101, "Name": "John Doe"},
{_id: 102, "Name": "David Miller"},
{_id: 103, "Name": "Sam Williams"}
]);
{
"acknowledged": true,
"insertedIds": [101, 102, 103]
}
View Original Data
db.creatingAliasDemo.find();
{ "_id": 101, "Name": "John Doe" }
{ "_id": 102, "Name": "David Miller" }
{ "_id": 103, "Name": "Sam Williams" }
Example: Creating Field Alias
Create an alias "FullName" for the "Name" field ?
db.creatingAliasDemo.aggregate([
{
$project: {
_id: 1,
"FullName": "$Name"
}
}
]);
{ "_id": 101, "FullName": "John Doe" }
{ "_id": 102, "FullName": "David Miller" }
{ "_id": 103, "FullName": "Sam Williams" }
Key Points
- The
$projectstage reshapes documents by including, excluding, or renaming fields. - Use
"aliasName": "$originalFieldName"syntax to create field aliases. - Set
_id: 1to include the _id field, or_id: 0to exclude it.
Conclusion
MongoDB's aggregation framework with $project provides a clean way to create field aliases. This approach transforms field names in query results without modifying the original document structure.
Advertisements
