通过变量索引更新MongoDB文档中的数组?
要通过变量索引更新MongoDB文档中的数组,请使用以下语法。在这里,yourIndexValue在索引值中,其中yourIndexVariableName是索引的变量名-
var yourIndexVariableName= yourIndexValue, anyVariableName= { "$set": {} }; yourVariableName["$set"]["yourFieldName."+yourIndexVariableName] = "yourValue"; db.yourCollectionName.update({ "_id": yourObjectId}, yourVariableName);
首先让我们创建一个包含文档的集合-
> db.updateByVariableDemo.insertOne({"StudentSubjects":["MySQL","Java","SQL Server","PL/SQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd553c37924bb85b3f4893a") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.updateByVariableDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd553c37924bb85b3f4893a"), "StudentSubjects" : [ "MySQL", "Java", "SQL Server", "PL/SQL" ] }
以下是通过变量索引更新MongoDB文档中数组的查询-
> var indexValue = 1, ... valueToUpdate= { "$set": {} }; > valueToUpdate["$set"]["StudentSubjects."+indexValue] = "MongoDB"; MongoDB > db.updateByVariableDemo.update({ "_id": ObjectId("5cd553c37924bb85b3f4893a") }, valueToUpdate) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次显示文档-
> db.updateByVariableDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd553c37924bb85b3f4893a"), "StudentSubjects" : [ "MySQL", "MongoDB", "SQL Server", "PL/SQL" ] }