在MongoDB中使用$ push更新数组
updateOne()
在MongoDB中使用。让我们创建一个包含文档的集合-> db.demo526.insertOne( ... { ... ... "CountryName": "US", ... "TeacherName": "Bob", ... "StudentInformation": [ ... { ... "Name": "Chris", ... "Subject": "MySQL", ... "ListOfMailId":[] ... }, ... { ... "Name": "David", ... "Subject": "MongoDB", ... "ListOfMailId":[] ... ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8af031437efc8605595b6b") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo526.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8af031437efc8605595b6b"), "CountryName" : "US", "TeacherName" : "Bob", "StudentInformation" : [ { "Name" : "Chris", "Subject" : "MySQL", "ListOfMailId" : [ ] }, { "Name" : "David", "Subject" : "MongoDB", "ListOfMailId" : [ ] } ] }
以下是使用$push更新数组的查询-
> db.demo526.updateOne( ... { ... _id:ObjectId("5e8af031437efc8605595b6b"), ... "StudentInformation": { "$elemMatch": { "Name": "David", "Subject": "MongoDB" }} ... }, ... { ... "$push": { "StudentInformation.$.ListOfMailId": { "MailId": "David@gmail.com" }} ... ... } ... ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo526.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8af031437efc8605595b6b"), "CountryName" : "US", "TeacherName" : "Bob", "StudentInformation" : [ { "Name" : "Chris", "Subject" : "MySQL", "ListOfMailId" : [ ] }, { "Name" : "David", "Subject" : "MongoDB", "ListOfMailId" : [ { "MailId" : "David@gmail.com" } ] } ] }