要使用多个条件更新数组,请在MongoDB中使用$push。让我们创建一个包含文档的集合-
> db.demo94.insertOne( ... { ... ... "Details" : [ ... { ... "Name" : "Chris", ... "Subject" : [] ... }, ... { ... "Name" : "David", ... "Subject" : [] ... }, ... { ... "Name" : "Bob", ... "Subject" : [] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2d553bb8903cdd865577a9") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo94.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2d553bb8903cdd865577a9"), "Details" : [ { "Name" : "Chris", "Subject" : [ ] }, { "Name" : "David", "Subject" : [ ] }, { "Name" : "Bob", "Subject" : [ ] } ] }
以下是在MongoDB中使用多个条件更新数组的查询-
> db.demo94.updateOne( ... { ... ... "Details": { "$elemMatch": { "Name": "David"}} ... }, ... { ... "$push": { "Details.$.Subject": { "Subject": "MongoDB" }} ... } ...); { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo94.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2d553bb8903cdd865577a9"), "Details" : [ { "Name" : "Chris", "Subject" : [ ] }, { "Name" : "David", "Subject" : [ { "Subject" : "MongoDB" } ] }, { "Name" : "Bob", "Subject" : [ ] } ] }