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
How can I rename a field for all documents in MongoDB?
To rename a field for all documents in MongoDB, use the $rename operator with an empty query filter to match all documents. This operation updates the field name across the entire collection.
Syntax
db.collectionName.updateMany(
{},
{ $rename: { "oldFieldName": "newFieldName" } }
);
Sample Data
Let's create a collection with student documents ?
db.renameFieldDemo.insertMany([
{ "StudentName": "John" },
{ "StudentName": "Carol" },
{ "StudentName": "Bob" },
{ "StudentName": "David" },
{ "StudentName": "Maxwell" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c7ee6c7559dd2396bcfbfbb"),
ObjectId("5c7ee6cb559dd2396bcfbfbc"),
ObjectId("5c7ee6cf559dd2396bcfbfbd"),
ObjectId("5c7ee6d3559dd2396bcfbfbe"),
ObjectId("5c7ee6d8559dd2396bcfbfbf")
]
}
Display all documents to verify the current structure ?
db.renameFieldDemo.find();
{ "_id": ObjectId("5c7ee6c7559dd2396bcfbfbb"), "StudentName": "John" }
{ "_id": ObjectId("5c7ee6cb559dd2396bcfbfbc"), "StudentName": "Carol" }
{ "_id": ObjectId("5c7ee6cf559dd2396bcfbfbd"), "StudentName": "Bob" }
{ "_id": ObjectId("5c7ee6d3559dd2396bcfbfbe"), "StudentName": "David" }
{ "_id": ObjectId("5c7ee6d8559dd2396bcfbfbf"), "StudentName": "Maxwell" }
Example: Rename Field for All Documents
Rename the field "StudentName" to "StudentFirstName" for all documents ?
db.renameFieldDemo.updateMany(
{},
{ $rename: { "StudentName": "StudentFirstName" } }
);
{
"acknowledged": true,
"matchedCount": 5,
"modifiedCount": 5
}
Verify Result
Check the documents to confirm the field has been renamed ?
db.renameFieldDemo.find();
{ "_id": ObjectId("5c7ee6c7559dd2396bcfbfbb"), "StudentFirstName": "John" }
{ "_id": ObjectId("5c7ee6cb559dd2396bcfbfbc"), "StudentFirstName": "Carol" }
{ "_id": ObjectId("5c7ee6cf559dd2396bcfbfbd"), "StudentFirstName": "Bob" }
{ "_id": ObjectId("5c7ee6d3559dd2396bcfbfbe"), "StudentFirstName": "David" }
{ "_id": ObjectId("5c7ee6d8559dd2396bcfbfbf"), "StudentFirstName": "Maxwell" }
Key Points
- Use
updateMany()for modern MongoDB versions instead of the legacyupdate()method. - An empty filter
{}matches all documents in the collection. - The operation only affects documents that contain the specified field.
Conclusion
The $rename operator with updateMany() efficiently renames fields across all documents in a collection. Use an empty query filter to target all documents and ensure the operation completes successfully.
Advertisements
