Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Is it possible to rename _id field after MongoDB group aggregation?
Yes, it is possible to rename the _id field after MongoDB group aggregation using the $project stage. This technique allows you to map the _id field to a new field name while excluding the original _id from the output.
Syntax
db.collection.aggregate([
{
$project: {
_id: 0,
newFieldName: "$_id",
otherFields: 1
}
}
]);
Sample Data
db.renameIdDemo.insertMany([
{"StudentName": "Chris"},
{"StudentName": "Robert"},
{"StudentName": "David"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9a1760353decbc2fc927c5"),
ObjectId("5c9a1765353decbc2fc927c6"),
ObjectId("5c9a176b353decbc2fc927c7")
]
}
Display all documents from the collection ?
db.renameIdDemo.find();
{ "_id" : ObjectId("5c9a1760353decbc2fc927c5"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c9a1765353decbc2fc927c6"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c9a176b353decbc2fc927c7"), "StudentName" : "David" }
Example: Rename _id to mainId
db.renameIdDemo.aggregate([
{
$project: {
_id: 0,
mainId: "$_id",
StudentName: 1
}
}
]);
{ "mainId" : ObjectId("5c9a1760353decbc2fc927c5"), "StudentName" : "Chris" }
{ "mainId" : ObjectId("5c9a1765353decbc2fc927c6"), "StudentName" : "Robert" }
{ "mainId" : ObjectId("5c9a176b353decbc2fc927c7"), "StudentName" : "David" }
Key Points
- Set
_id: 0to exclude the original_idfield from output - Use
"$_id"syntax to reference the original_idvalue - Include other fields using
fieldName: 1to preserve them
Conclusion
Renaming the _id field in MongoDB aggregation is straightforward using $project. Simply exclude the original _id and map its value to a new field name using the "$_id" reference syntax.
Advertisements
