您可以为此使用$set运算符。首先让我们创建一个包含文档的集合-
> db.pullAllElementDemo.insertOne( ... { ... "StudentId":101, ... "StudentDetails" : [ ... { ... ... "StudentName": "Carol", ... "StudentAge":21, ... "StudentCountryName":"US" ... }, ... { ... "StudentName": "Chris", ... "StudentAge":24, ... "StudentCountryName":"AUS" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ccdd9c8685b30d09a7111e4") } > db.pullAllElementDemo.insertOne( ... { ... "StudentId":102, ... "StudentDetails" : [ ... { ... ... "StudentName": "Robert", ... "StudentAge":27, ... "StudentCountryName":"UK" ... }, ... { ... "StudentName": "David", ... "StudentAge":23, ... "StudentCountryName":"US" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ccdd9f7685b30d09a7111e5") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.pullAllElementDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ccdd9c8685b30d09a7111e4"), "StudentId" : 101, "StudentDetails" : [ { "StudentName" : "Carol", "StudentAge" : 21, "StudentCountryName" : "US" }, { "StudentName" : "Chris", "StudentAge" : 24, "StudentCountryName" : "AUS" } ] } { "_id" : ObjectId("5ccdd9f7685b30d09a7111e5"), "StudentId" : 102, "StudentDetails" : [ { "StudentName" : "Robert", "StudentAge" : 27, "StudentCountryName" : "UK" }, { "StudentName" : "David", "StudentAge" : 23, "StudentCountryName" : "US" } ] }
以下是从MongoDB中无条件提取数组中所有元素的查询。在这里,我们使用$set删除了带有StudentId 102的StudentDetails-
> db.pullAllElementDemo.update( {StudentId:102}, { "$set": { "StudentDetails": [] }} ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们显示上述集合中的所有文档,以检查数组中的那些特定元素是否已被拉出-
> db.pullAllElementDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ccdd9c8685b30d09a7111e4"), "StudentId" : 101, "StudentDetails" : [ { "StudentName" : "Carol", "StudentAge" : 21, "StudentCountryName" : "US" }, { "StudentName" : "Chris", "StudentAge" : 24, "StudentCountryName" : "AUS" } ] } { "_id" : ObjectId("5ccdd9f7685b30d09a7111e5"), "StudentId" : 102, "StudentDetails" : [ ] }