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 equivalent of SELECT field AS `anothername`?
In MySQL, we give an alias name for a column. Similarly, you can give an alias name for field name in MongoDB using the $project stage in aggregation pipeline.
Syntax
db.collectionName.aggregate([
{ "$project": {
"_id": 0,
"aliasName": "$originalFieldName"
}}
]);
Sample Data
Let us first create a collection with documents ?
db.selectFieldAsAnotherNameDemo.insertMany([
{"Name": "Larry"},
{"Name": "Robert"},
{"Name": "Sam"},
{"Name": "Mike"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9d448827b86948e204ca91"),
ObjectId("5c9d449027b86948e204ca92"),
ObjectId("5c9d449527b86948e204ca93"),
ObjectId("5c9d449927b86948e204ca94")
]
}
Following is the query to display all documents from a collection with the help of find() method ?
db.selectFieldAsAnotherNameDemo.find().pretty();
{ "_id" : ObjectId("5c9d448827b86948e204ca91"), "Name" : "Larry" }
{ "_id" : ObjectId("5c9d449027b86948e204ca92"), "Name" : "Robert" }
{ "_id" : ObjectId("5c9d449527b86948e204ca93"), "Name" : "Sam" }
{ "_id" : ObjectId("5c9d449927b86948e204ca94"), "Name" : "Mike" }
Example
Following is the query for MongoDB equivalent of SELECT field AS `anothername` ?
db.selectFieldAsAnotherNameDemo.aggregate([
{ "$project": {
"_id": 0,
"StudentName": "$Name"
}}
]);
{ "StudentName" : "Larry" }
{ "StudentName" : "Robert" }
{ "StudentName" : "Sam" }
{ "StudentName" : "Mike" }
Key Points
- Use
$projectstage in aggregation pipeline to create field aliases. - Set
"_id": 0to exclude the ObjectId from output. - Reference original field with
"$fieldName"syntax.
Conclusion
MongoDB's $project stage provides field aliasing similar to SQL's AS clause. Use the aggregation pipeline to rename fields in query results with custom alias names.
Advertisements
