如何使用MongoDB $ pull删除数组中的文档?
您需要与$pull运算符一起使用update命令来删除数组中的文档。让我们创建包含文档的集合。以下是查询
> db.deleteDocumentsDemo.insertOne( ... { ... "_id":100, ... "StudentsDetails" : [ ... { ... "StudentId" : 1, ... "StudentName" : "John" ... }, ... { ... "StudentId" : 2, ... "StudentName" : "Carol" ... }, ... { ... "StudentId" : 3, ... "StudentName" : "Sam" ... }, ... { ... "StudentId" : 4, ... "StudentName" : "Mike" ... } ... ] ... } ... ... ); { "acknowledged" : true, "insertedId" : 100 } > db.deleteDocumentsDemo.insertOne( ... { ... "_id":200, ... "StudentsDetails" : [ ... { ... "StudentId" : 5, ... "StudentName" : "David" ... }, ... { ... "StudentId" : 6, ... "StudentName" : "Ramit" ... }, ... { ... "StudentId" : 7, ... "StudentName" : "Adam" ... }, ... { ... "StudentId" : 8, ... "StudentName" : "Larry" ... } ... ] ... } ... ... ); { "acknowledged" : true, "insertedId" : 200 }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.deleteDocumentsDemo.find().pretty();
这将产生以下输出
{ "_id" : 100, "StudentsDetails" : [ { "StudentId" : 1, "StudentName" : "John" }, { "StudentId" : 2, "StudentName" : "Carol" }, { "StudentId" : 3, "StudentName" : "Sam" }, { "StudentId" : 4, "StudentName" : "Mike" } ] } { "_id" : 200, "StudentsDetails" : [ { "StudentId" : 5, "StudentName" : "David" }, { "StudentId" : 6, "StudentName" : "Ramit" }, { "StudentId" : 7, "StudentName" : "Adam" }, { "StudentId" : 8, "StudentName" : "Larry" } ] }
以下是删除数组中文档的查询
> db.deleteDocumentsDemo.update({}, ... {$pull: {StudentsDetails: {StudentName: "David"}}}, ... {multi: true}); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 1 })
让我们检查文件是否被删除。以下是查询
> db.deleteDocumentsDemo.find().pretty();
这将产生以下输出
{ "_id" : 100, "StudentsDetails" : [ { "StudentId" : 1, "StudentName" : "John" }, { "StudentId" : 2, "StudentName" : "Carol" }, { "StudentId" : 3, "StudentName" : "Sam" }, { "StudentId" : 4, "StudentName" : "Mike" } ] } { "_id" : 200, "StudentsDetails" : [ { "StudentId" : 6, "StudentName" : "Ramit" }, { "StudentId" : 7, "StudentName" : "Adam" }, { "StudentId" : 8, "StudentName" : "Larry" } ] }
查看上面的示例输出,已删除值为5的“StudentId”,即StudentName“David”。