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
Renaming column name in a MongoDB collection?
To rename a field (column) name in a MongoDB collection, use the $rename operator. This operator allows you to change field names across multiple documents in a single operation.
Syntax
db.collectionName.updateMany(
{},
{ $rename: { "oldFieldName": "newFieldName" } }
);
Sample Data
Let us create a collection with sample documents ?
db.renamingColumnNameDemo.insertMany([
{ "StudentName": "Larry", "Age": 23 },
{ "StudentName": "Sam", "Age": 26 },
{ "StudentName": "Robert", "Age": 27 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9ee2c6d628fa4220163b9a"),
ObjectId("5c9ee2d0d628fa4220163b9b"),
ObjectId("5c9ee2dbd628fa4220163b9c")
]
}
Display all documents to verify the initial structure ?
db.renamingColumnNameDemo.find();
{
"_id": ObjectId("5c9ee2c6d628fa4220163b9a"),
"StudentName": "Larry",
"Age": 23
}
{
"_id": ObjectId("5c9ee2d0d628fa4220163b9b"),
"StudentName": "Sam",
"Age": 26
}
{
"_id": ObjectId("5c9ee2dbd628fa4220163b9c"),
"StudentName": "Robert",
"Age": 27
}
Example: Rename Field
Rename the "Age" field to "StudentAge" across all documents ?
db.renamingColumnNameDemo.updateMany(
{},
{ $rename: { "Age": "StudentAge" } }
);
{
"acknowledged": true,
"matchedCount": 3,
"modifiedCount": 3
}
Verify Result
Check that the field has been successfully renamed ?
db.renamingColumnNameDemo.find();
{
"_id": ObjectId("5c9ee2c6d628fa4220163b9a"),
"StudentName": "Larry",
"StudentAge": 23
}
{
"_id": ObjectId("5c9ee2d0d628fa4220163b9b"),
"StudentName": "Sam",
"StudentAge": 26
}
{
"_id": ObjectId("5c9ee2dbd628fa4220163b9c"),
"StudentName": "Robert",
"StudentAge": 27
}
Conclusion
The $rename operator efficiently renames fields across all documents in a collection. Use updateMany() with an empty filter {} to apply the rename operation to all documents simultaneously.
Advertisements
