- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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