- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating alias in a MongoDB query?
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" }
Advertisements