要将新项目添加到数组,可以使用$push运算符。让我们首先实现以下查询以创建包含文档的集合:
> db.updateDemo.insertOne({"StudentName":"Larry","StudentCoreSubject":["Java","C"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c98ba78330fd0aa0d2fe4c9") } >db.updateDemo.insertOne({"StudentName":"Robert","StudentCoreSubject":["C++","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c98ba8b330fd0aa0d2fe4ca") } > db.updateDemo.insertOne({"StudentName":"Chris","StudentCoreSubject":["Python"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c98ba9b330fd0aa0d2fe4cb") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.updateDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c98ba78330fd0aa0d2fe4c9"), "StudentName" : "Larry", "StudentCoreSubject" : [ "Java", "C" ] } { "_id" : ObjectId("5c98ba8b330fd0aa0d2fe4ca"), "StudentName" : "Robert", "StudentCoreSubject" : [ "C++", "MongoDB" ] } { "_id" : ObjectId("5c98ba9b330fd0aa0d2fe4cb"), "StudentName" : "Chris", "StudentCoreSubject" : [ "Python" ] }
以下是将新项目添加到数组的查询
> db.updateDemo.update( { _id:ObjectId("5c98ba78330fd0aa0d2fe4c9") }, { $push: { "StudentCoreSubject": "MySQL" } }); Updated 1 existing record(s) in 2ms WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
现在检查项目是否插入到数组中
> db.updateDemo.find().pretty();
这将产生以下输出。字符串“ MySQL”已成功插入ID 5c98ba78330fd0aa0d2fe4c9
{ "_id" : ObjectId("5c98ba78330fd0aa0d2fe4c9"), "StudentName" : "Larry", "StudentCoreSubject" : [ "Java", "C", "MySQL" ] } { "_id" : ObjectId("5c98ba8b330fd0aa0d2fe4ca"), "StudentName" : "Robert", "StudentCoreSubject" : [ "C++", "MongoDB" ] } { "_id" : ObjectId("5c98ba9b330fd0aa0d2fe4cb"), "StudentName" : "Chris", "StudentCoreSubject" : [ "Python" ] }