如何从 MongoDB 中的数组中提取多个对象?
要从数组中提取多个对象,可以使用 $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" } ] }
看看上面的示例输出,已从数组中移除多个对象。
广告