

- 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
Is it possible to rename _id field after MongoDB group aggregation?
Yes, it is possible to rename using aggregation. Let us first create a collection with documents
> db.renameIdDemo.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a1760353decbc2fc927c5") } > db.renameIdDemo.insertOne({"StudentName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a1765353decbc2fc927c6") } > db.renameIdDemo.insertOne({"StudentName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a176b353decbc2fc927c7") }
Following is the query to display all documents from a collection with the help of find() method
> db.renameIdDemo.find();
This will produce the following output
{ "_id" : ObjectId("5c9a1760353decbc2fc927c5"), "StudentName" : "Chris" } { "_id" : ObjectId("5c9a1765353decbc2fc927c6"), "StudentName" : "Robert" } { "_id" : ObjectId("5c9a176b353decbc2fc927c7"), "StudentName" : "David" }
Following is the query to rename _id field:
> db.renameIdDemo.aggregate({ $project: { ... _id: 0, ... mainId: "$_id", ... count: 1, ... sum: 1 ... } ... } ... );
This will produce the following output. We have renamed _id to mainId;
{ "mainId" : ObjectId("5c9a1760353decbc2fc927c5") } { "mainId" : ObjectId("5c9a1765353decbc2fc927c6") } { "mainId" : ObjectId("5c9a176b353decbc2fc927c7") }
- Related Questions & Answers
- MongoDB aggregation framework match OR is possible?
- Is it possible to sum two fields in MongoDB using the Aggregation framework?
- Is it possible to use MongoDB field value as pattern in $regex?
- Is it possible to use MongoDB field value as a pattern in $regex?
- Hide id field in MongoDB
- Is it possible to delete everything after a 'space' in a MySQL field?
- MongoDB aggregation framework with group query example?
- Is it possible to use MongoDB capped collection?
- MongoDB query to group several fields using aggregation framework?
- Is it possible to resume java execution after exception occurs?
- Sort and Group in one MongoDB aggregation query?
- MongoDB aggregation group and remove duplicate array values?
- MongoDB aggregation to fetch documents with specific field value?
- Is it possible to cast in a MongoDB Query?
- Check if it is possible to sort the array after rotating it in Python
Advertisements