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. The MongoDB equivalent syntax is as follows

db.yourCollectionName.aggregate(
[
   { "$project": {
      "_id": 0,
      "anyAliasName": "$yourFieldName"
   }}
]);

Let us first create a collection with documents

> db.selectFieldAsAnotherNameDemo.insertOne({"Name":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d448827b86948e204ca91")
}
> db.selectFieldAsAnotherNameDemo.insertOne({"Name":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d449027b86948e204ca92")
}
> db.selectFieldAsAnotherNameDemo.insertOne({"Name":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d449527b86948e204ca93")
}
> db.selectFieldAsAnotherNameDemo.insertOne({"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9d449927b86948e204ca94")
}

Following is the query to display all documents from a collection with the help of find() method

> db.selectFieldAsAnotherNameDemo.find().pretty();

This will produce the following output

{ "_id" : ObjectId("5c9d448827b86948e204ca91"), "Name" : "Larry" }
{ "_id" : ObjectId("5c9d449027b86948e204ca92"), "Name" : "Robert" }
{ "_id" : ObjectId("5c9d449527b86948e204ca93"), "Name" : "Sam" }
{ "_id" : ObjectId("5c9d449927b86948e204ca94"), "Name" : "Mike" }

Following is the query for MongoDB equivalent of SELECT field AS `anothername`

> db.selectFieldAsAnotherNameDemo.aggregate(
... [
...    { "$project": {
...       "_id": 0,
...       "StudentName": "$Name"
...    }}
... ]);

This will produce the following output

{ "StudentName" : "Larry" }
{ "StudentName" : "Robert" }
{ "StudentName" : "Sam" }
{ "StudentName" : "Mike" }

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements