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
MongoDB query to change simple field into an object?
To change a simple field into an object in MongoDB, use the $rename operator with a temporary field approach. This involves renaming the field to a temporary name, then renaming it back with the desired object structure using dot notation.
Syntax
db.collection.updateMany(
{},
{ $rename: { "fieldName": "tempField" } }
);
db.collection.updateMany(
{},
{ $rename: { "tempField": "objectName.nestedField" } }
);
Sample Data
db.changeSimpleFieldDemo.insertOne({
"StudentMarks": 58,
"StudentSubject": "MySQL"
});
{
"acknowledged": true,
"insertedId": ObjectId("5e0847a825ddae1f53b62205")
}
Let us view the inserted document ?
db.changeSimpleFieldDemo.find();
{ "_id": ObjectId("5e0847a825ddae1f53b62205"), "StudentMarks": 58, "StudentSubject": "MySQL" }
Example: Transform Fields into Nested Object
Transform "StudentMarks" and "StudentSubject" into a nested "Student" object ?
db.changeSimpleFieldDemo.updateMany(
{},
{ $rename: { "StudentMarks": "tempMarks", "StudentSubject": "tempSubject" } }
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
db.changeSimpleFieldDemo.updateMany(
{},
{ $rename: { "tempMarks": "Student.Marks", "tempSubject": "Student.Subject" } }
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
Verify Result
db.changeSimpleFieldDemo.find();
{
"_id": ObjectId("5e0847a825ddae1f53b62205"),
"Student": {
"Marks": 58,
"Subject": "MySQL"
}
}
Key Points
- Use temporary field names to avoid conflicts during the renaming process.
- Dot notation creates nested object structures automatically.
-
updateMany()with empty filter{}updates all documents in the collection.
Conclusion
The $rename operator with temporary fields effectively transforms simple fields into nested objects. This two-step approach ensures clean restructuring of document schemas in MongoDB collections.
Advertisements
