- 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
How can I change the field name in MongoDB?
To change the field name, use the $project. Let us create a collection with documents −
> db.demo517.insertOne({"Name":"Chris Brown"});{ "acknowledged" : true, "insertedId" : ObjectId("5e88a2a2987b6e0e9d18f595") } > db.demo517.insertOne({"Name":"David Miller"});{ "acknowledged" : true, "insertedId" : ObjectId("5e88a2ab987b6e0e9d18f596") } > db.demo517.insertOne({"Name":"John Doe"});{ "acknowledged" : true, "insertedId" : ObjectId("5e88a2b1987b6e0e9d18f597") }
Display all documents from a collection with the help of find() method −
> db.demo517.find();
This will produce the following output −
{ "_id" : ObjectId("5e88a2a2987b6e0e9d18f595"), "Name" : "Chris Brown" } { "_id" : ObjectId("5e88a2ab987b6e0e9d18f596"), "Name" : "David Miller" } { "_id" : ObjectId("5e88a2b1987b6e0e9d18f597"), "Name" : "John Doe" }
Following is the query to change the field name −
> db.demo517.aggregate([{$project:{FullName:"$Name"}}]);
This will produce the following output −
{ "_id" : ObjectId("5e88a2a2987b6e0e9d18f595"), "FullName" : "Chris Brown" } { "_id" : ObjectId("5e88a2ab987b6e0e9d18f596"), "FullName" : "David Miller" } { "_id" : ObjectId("5e88a2b1987b6e0e9d18f597"), "FullName" : "John Doe" }
Advertisements