要更新MongDB中的最佳文档,请使用UPDATE()
和positional($)运算符。让我们创建一个包含文档的集合-
> db.demo643.insertOne({ ... details : [ ... { ... "CountryName":"US", ... StudentDetails:[{Name:"Chris"},{SubjectName:"MySQL"}] ... }, ... ... { ... "CountryName":"UK", ... StudentDetails:[{Name:"Bob"},{SubjectName:"Java"}] ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5e9c737f6c954c74be91e6e3") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo643.find();
这将产生以下输出-
{ "_id" : ObjectId("5e9c737f6c954c74be91e6e3"), "details" : [ { "CountryName" : "US", "StudentDetails" : [ { "Name" : "Chris" }, { "SubjectName" : "MySQL" } ] }, { "CountryName" : "UK", "StudentDetails" : [ { "Name" : "Bob" }, { "SubjectName" : "Java" } ] } ] }
以下是更新MongoDB中嵌套的嵌入式文档的查询-
> db.demo643.update({"details.CountryName": "UK"}, {"$push": {"details.$.StudentDetails": {Marks:78}}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo643.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e9c737f6c954c74be91e6e3"), "details" : [ { "CountryName" : "US", "StudentDetails" : [ { "Name" : "Chris" }, { "SubjectName" : "MySQL" } ] }, { "CountryName" : "UK", "StudentDetails" : [ { "Name" : "Bob" }, { "SubjectName" : "Java" }, { "Marks" : 78 } ] } ] }