使用$set替换数组中的值。首先让我们创建一个包含文档的集合-
> db.replaceValueInArrayDemo.insertOne({"StudentScores":[45,56,78]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7f0421a844af18acdffb7") } > db.replaceValueInArrayDemo.insertOne({"StudentScores":[33,90,67]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7f0521a844af18acdffb8") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.replaceValueInArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd7f0421a844af18acdffb7"), "StudentScores" : [ 45, 56, 78 ] } { "_id" : ObjectId("5cd7f0521a844af18acdffb8"), "StudentScores" : [ 33, 90, 67 ] }
以下是替换数组中的值的查询-
> db.replaceValueInArrayDemo.update({_id: ObjectId("5cd7f0421a844af18acdffb7"), StudentScores:45}, {$set: {'StudentScores.$': 99}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查文档-
> db.replaceValueInArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd7f0421a844af18acdffb7"), "StudentScores" : [ 99, 56, 78 ] } { "_id" : ObjectId("5cd7f0521a844af18acdffb8"), "StudentScores" : [ 33, 90, 67 ] }