要提取值,请使用$pull并设置multi:true。首先让我们创建一个包含文档的集合-
> db.demo392.insertOne( ... { ... Name: 'Chris', ... details: [ ... { ... _id: '101' ... ... }, ... { ... _id: '102' ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5d2b3322064be7ab44e802") } > > db.demo392.insertOne( ... { ... Name: 'Chris', ... details: [ ... { ... _id: '104' ... ... }, ... { ... _id: '101' ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5d2b3422064be7ab44e803") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo392.find();
这将产生以下输出-
{ "_id" : ObjectId("5e5d2b3322064be7ab44e802"), "Name" : "Chris", "details" : [ { "_id" : "101" }, { "_id" : "102" } ] } { "_id" : ObjectId("5e5d2b3422064be7ab44e803"), "Name" : "Chris", "details" : [ { "_id" : "104" }, { "_id" : "101" } ] }
以下是从数组查询$pull-
> db.demo392.update( ... { }, ... { $pull: { details: { _id: '101' } } }, ... { multi: true } ... ) WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo392.find();
这将产生以下输出-
{ "_id" : ObjectId("5e5d2b3322064be7ab44e802"), "Name" : "Chris", "details" : [ { "_id" : "102" } ] } { "_id" : ObjectId("5e5d2b3422064be7ab44e803"), "Name" : "Chris", "details" : [ { "_id" : "104" } ] }