 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to change simple field into an object?
Fir this, you can use $rename. Let us first create a collection with documents −
> db.changeSimpleFieldDemo.insertOne({"StudentMarks":58,"StudentSubject":"MySQL"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e0847a825ddae1f53b62205") } Following is the query to display all documents from a collection with the help of find() method −
> db.changeSimpleFieldDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5e0847a825ddae1f53b62205"), "StudentMarks" : 58, "StudentSubject" : "MySQL" } Here is the query to change a field into an object. The “obj” field is a temporary field name we have used below −
> db.changeSimpleFieldDemo.update({}, {$rename: {Student: 'obj'}}, {multi: true}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 }) > db.changeSimpleFieldDemo.update({}, ... {$rename: {obj: 'Student.Marks', discountType: 'Student.Subject'}}, ... {multi: true}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })Advertisements
 