要更新数组中的元素,请在MongoDB中使用$set。让我们创建一个包含文档的集合-
> db.demo494.insertOne( ... { ... ... "CollegeDetails" : [ ... { ... "CollegeName" : "MIT", ... "Fees" : 80000 ... }, ... { ... "CollegeName" : "SU", ... "Fees" : 90000 ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5e84a5c1b0f3fa88e22790c9") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo494.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e84a5c1b0f3fa88e22790c9"), "CollegeDetails" : [ { "CollegeName" : "MIT", "Fees" : 80000 }, { "CollegeName" : "SU", "Fees" : 90000 } ] }
以下是更新MongoDB中数组内元素的查询-
> db.demo494.update( ... ... { ... "CollegeDetails.CollegeName": "MIT" ... }, ... ... { ... $set: ... { ... "CollegeDetails.$.Fees" : 100000 ... } ... } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo494.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e84a5c1b0f3fa88e22790c9"), "CollegeDetails" : [ { "CollegeName" : "MIT", "Fees" : 100000 }, { "CollegeName" : "SU", "Fees" : 90000 } ] }