为此,您可以使用$rename。首先让我们创建一个包含文档的集合-
> db.changeSimpleFieldDemo.insertOne({"StudentMarks":58,"StudentSubject":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e0847a825ddae1f53b62205") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.changeSimpleFieldDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5e0847a825ddae1f53b62205"), "StudentMarks" : 58, "StudentSubject" : "MySQL" }
这是将字段更改为对象的查询。“ obj”字段是我们在下面使用的临时字段名称-
> 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 })