MongoDB 查询以更换数组中的值?
使用 $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 ] }
广告