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 })