要从数组中提取多个对象,可以使用$pull运算符。首先让我们创建一个包含文档的集合-
> db.pullMultipleObjectsDemo.insertOne( ... { ... "ClientId" : "100", ... "ClientName" : "John", ... "ClientPersonalDetails" : [ ... { ... "ClientCountryName" : "US", ... "ClientProjectName" : "Online Book Store", ... ... }, ... { ... "ClientCountryName" : "AUS", ... "ClientProjectName" : "Online Fee Management", ... ... }, ... { ... "ClientCountryName" : "UK", ... "ClientProjectName" : "Online Pig Dice Game", ... ... }, ... { ... "ClientCountryName" : "ANGOLA", ... "ClientProjectName" : "Online Hospital Management", ... ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc7d0748f9e6ff3eb0ce43d") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.pullMultipleObjectsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc7d0748f9e6ff3eb0ce43d"), "ClientId" : "100", "ClientName" : "John", "ClientPersonalDetails" : [ { "ClientCountryName" : "US", "ClientProjectName" : "Online Book Store" }, { "ClientCountryName" : "AUS", "ClientProjectName" : "Online Fee Management" }, { "ClientCountryName" : "UK", "ClientProjectName" : "Online Pig Dice Game" }, { "ClientCountryName" : "ANGOLA", "ClientProjectName" : "Online Hospital Management" } ] }
以下是从数组中提取多个对象的查询-
> db.pullMultipleObjectsDemo.update( ... {"_id": ObjectId("5cc7d0748f9e6ff3eb0ce43d")}, ... {"$pull":{"ClientPersonalDetails":{"ClientProjectName":{$in:["Online Book Store","Online Pig Dice Game"]}}}} ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们显示集合中的所有文档,以检查对象是否已从数组中删除。查询如下-
> db.pullMultipleObjectsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc7d0748f9e6ff3eb0ce43d"), "ClientId" : "100", "ClientName" : "John", "ClientPersonalDetails" : [ { "ClientCountryName" : "AUS", "ClientProjectName" : "Online Fee Management" }, { "ClientCountryName" : "ANGOLA", "ClientProjectName" : "Online Hospital Management" } ] }
查看上面的示例输出,已从数组中删除了多个对象。