首先让我们创建一个包含文档的集合
> db.updateListOfKeyValuesDemo.insertOne( { "StudentDetails":[ { "StudentName":"John", "StudentAge":23, "StudentCountryName":"US" }, { "StudentName":"Carol", "StudentAge":24, "StudentCountryName":"UK" }, { "StudentName":"Bob", "StudentAge":22, "StudentCountryName":"AUS" } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5c9b5b759882024390176545") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.updateListOfKeyValuesDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9b5b759882024390176545"), "StudentDetails" : [ { "StudentName" : "John", "StudentAge" : 23, "StudentCountryName" : "US" }, { "StudentName" : "Carol", "StudentAge" : 24, "StudentCountryName" : "UK" }, { "StudentName" : "Bob", "StudentAge" : 22, "StudentCountryName" : "AUS" } ] }
以下是更新MongoDB中json列表中的键值的查询
> var documentFromCollection = db.updateListOfKeyValuesDemo.findOne({ ... "_id": ObjectId("5c9b5b759882024390176545") ... }); > > documentFromCollection.StudentDetails.forEach(function(updateStudent) { ... updateStudent.StudentName = "Ramit"; ... }); > db.updateListOfKeyValuesDemo.update( ... { "_id": documentFromCollection ._id }, ... { "$set": { "StudentDetails": documentFromCollection.StudentDetails } } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们检查键值列表是否已更新
> db.updateListOfKeyValuesDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9b5b759882024390176545"), "StudentDetails" : [ { "StudentName" : "Ramit", "StudentAge" : 23, "StudentCountryName" : "US" }, { "StudentName" : "Ramit", "StudentAge" : 24, "StudentCountryName" : "UK" }, { "StudentName" : "Ramit", "StudentAge" : 22, "StudentCountryName" : "AUS" } ] }