

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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" }
- Related Questions & Answers
- How to use alias in MySQL select query?
- Creating views in MongoDB
- Is there a way to create a MySQL “alias” while creating a VIEW?
- Creating hierarchical JSON in MongoDB?
- Creating an index on a nested MongoDB field?
- Set 'alias' for all the column names in a single MySQL query
- What is a Cypress Alias?
- MongoDB query for a single field
- Query MongoDB for a nested search
- MongoDB query to rename a collection?
- Update multiple rows in a single MongoDB query?
- Understanding MongoDB Query Plan
- MongoDB - Query embedded documents?
- How do I query a MongoDB collection?
- How to query MongoDB with a LIMIT?
Advertisements