使用 $push 更新 MongoDB 中的数组
要使用 $push 更新数组,请在 MongoDB 中使用 updateOne()。我们使用文档创建一个集合 -
> 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" } ] }
] }
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP