如何在MongoDB中的 json 列表里更新键的值?
我们首先使用文档创建一个集合
> 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" } ] }
广告