要更新内部字段,请使用以下语法-
db.yourCollectionName.update({"_id" : yourObjectId}, {$set : {"yourOuterFieldName.yourInnerFieldName" :yourValue}});
首先让我们创建一个包含文档的集合-
> db.updateDocumentDemo.insertOne( ... { ... ... "StudentDetails" : { ... "StudentFirstName" : "Adam", ... "StudentLastName" : "Samith" ... }, ... "StudentOtherDetails" : { ... "StudentFavouriteSubject" : "MySQL", ... "StudentScore" : 45 ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd50bb32cba06f46efe9efe") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.updateDocumentDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd50bb32cba06f46efe9efe"), "StudentDetails" : { "StudentFirstName" : "Adam", "StudentLastName" : "Samith" }, "StudentOtherDetails" : { "StudentFavouriteSubject" : "MySQL", "StudentScore" : 45 } }
以下是更新MongoDB中文档的查询-
> db.updateDocumentDemo.update({"_id" : ObjectId("5cd50bb32cba06f46efe9efe")}, ... {$set : {"StudentOtherDetails.StudentFavouriteSubject" :"MongoDB"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次显示文档-
> db.updateDocumentDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd50bb32cba06f46efe9efe"), "StudentDetails" : { "StudentFirstName" : "Adam", "StudentLastName" : "Samith" }, "StudentOtherDetails" : { "StudentFavouriteSubject" : "MongoDB", "StudentScore" : 45 } }