您可以使用位置运算符$。首先让我们创建一个包含文档的集合-
> db.replaceAnArrayFieldValueDemo.insertOne({"StudentTechnicalSubjects":["MySQL","SQL Server","PL/SQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cea41e0ef71edecf6a1f68f") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.replaceAnArrayFieldValueDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cea41e0ef71edecf6a1f68f"), "StudentTechnicalSubjects" : [ "MySQL", "SQL Server", "PL/SQL" ] }
以下是替换数组字段值的查询。在这里,我们使用“ MongoDB”更新“ SQL Server”-
> db.replaceAnArrayFieldValueDemo.update( {"StudentTechnicalSubjects":"SQL Server"}, { $set: { 'StudentTechnicalSubjects.$': "MongoDB" }} ); WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
让我们再次检查文档-
> db.replaceAnArrayFieldValueDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cea41e0ef71edecf6a1f68f"), "StudentTechnicalSubjects" : [ "MySQL", "MongoDB", "PL/SQL" ] }