Creating alias in a MongoDB query?

MongoDBDatabaseBig Data Analytics

You can use aggregate framework to create an alias. Let us first create a collection with documents −

> db.creatingAliasDemo.insertOne({_id:101,"Name":"John Doe"});
{ "acknowledged" : true, "insertedId" : 101 }
> db.creatingAliasDemo.insertOne({_id:102,"Name":"David Miller"});
{ "acknowledged" : true, "insertedId" : 102 }
> db.creatingAliasDemo.insertOne({_id:103,"Name":"Sam Williams"});
{ "acknowledged" : true, "insertedId" : 103 }

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

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

This will produce the following output −

{ "_id" : 101, "Name" : "John Doe" }
{ "_id" : 102, "Name" : "David Miller" }
{ "_id" : 103, "Name" : "Sam Williams" }

Following is the query to create alias in a query −

> db.creatingAliasDemo.aggregate(
...    [
...       {
...          $project: {
...             _id:1,
...             "FullName":"$Name"
...          }
...       }
...    ]
... );

This will produce the following output −

{ "_id" : 101, "FullName" : "John Doe" }
{ "_id" : 102, "FullName" : "David Miller" }
{ "_id" : 103, "FullName" : "Sam Williams" }
raja
Published on 30-Apr-2019 09:00:29
Advertisements