如何在 MongoDB 使用 $pull 删除数组内的文档?
你需要使用 update 命令和 $pull 运算符来删除数组中的文档。让我们创建一个带有文档的集合。以下是查询
> 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" } ] }
查看上面的示例输出,“StudentId”的值为 5,即“David”的“StudentName”已被删除。
广告