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 to re-map the fields of a MongoDB collection?
To re-map the fields of a MongoDB collection, use $rename operator with update() or updateMany(). This operator allows you to rename field names across documents in your collection.
Syntax
db.collection.updateMany(
{},
{ $rename: { "oldFieldName": "newFieldName" } }
);
Sample Data
Let us create a collection with sample documents ?
db.demo171.insertMany([
{
"Name": "Chris",
"Details": {
"SubjectName": "MySQL",
"CountryName": "US"
}
},
{
"Name": "John",
"Details": {
"SubjectName": "MongoDB",
"CountryName": "UK"
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3837399e4f06af551997e0"),
ObjectId("5e3837399e4f06af551997e1")
]
}
Display all documents from the collection ?
db.demo171.find().pretty();
{
"_id": ObjectId("5e3837399e4f06af551997e0"),
"Name": "Chris",
"Details": {
"SubjectName": "MySQL",
"CountryName": "US"
}
}
{
"_id": ObjectId("5e3837399e4f06af551997e1"),
"Name": "John",
"Details": {
"SubjectName": "MongoDB",
"CountryName": "UK"
}
}
Example: Rename Top-Level Field
Rename the "Name" field to "StudentName" across all documents ?
db.demo171.updateMany(
{},
{ $rename: { "Name": "StudentName" } }
);
{
"acknowledged": true,
"matchedCount": 2,
"modifiedCount": 2
}
Verify Result
db.demo171.find().pretty();
{
"_id": ObjectId("5e3837399e4f06af551997e0"),
"Details": {
"SubjectName": "MySQL",
"CountryName": "US"
},
"StudentName": "Chris"
}
{
"_id": ObjectId("5e3837399e4f06af551997e1"),
"Details": {
"SubjectName": "MongoDB",
"CountryName": "UK"
},
"StudentName": "John"
}
Example: Rename Nested Field
Rename nested field "SubjectName" to "Subject" ?
db.demo171.updateMany(
{},
{ $rename: { "Details.SubjectName": "Details.Subject" } }
);
{
"acknowledged": true,
"matchedCount": 2,
"modifiedCount": 2
}
Key Points
- Use
{}as filter to rename fields across all documents in the collection. - For nested fields, use dot notation like "parent.child".
-
updateMany()is preferred over the legacyupdate()method. - If the old field doesn't exist, the operation is ignored for that document.
Conclusion
The $rename operator provides an efficient way to restructure your MongoDB collections by changing field names. Use updateMany() with an empty filter to rename fields across all documents in the collection.
Advertisements
