从嵌套在MongoDB中另一个数组中的数组中删除特定记录?
要删除特定记录,请使用$pull运算符。首先让我们创建一个包含文档的集合-
> dbdeletingSpecificRecordDemoinsertOne( { "StudentDetails": [ { "StudentName": "John", "StudentSubjectDetails": [ { "Subject": "MongoDB", "Marks":45 }, { "Subject": "MySQL", "Marks":67 } ] } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cf2210ab64a577be5a2bc06") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> dbdeletingSpecificRecordDemofind()pretty();
这将产生以下文件-
{ "_id" : ObjectId("5cf2210ab64a577be5a2bc06"), "StudentDetails" : [ { "StudentName" : "John", "StudentSubjectDetails" : [ { "Subject" : "MongoDB", "Marks" : 45 }, { "Subject" : "MySQL", "Marks" : 67 } ] } ] }
这是从嵌套在另一个数组中的数组中删除特定记录的查询-
> dbdeletingSpecificRecordDemoupdate({"_id": ObjectId("5cf2210ab64a577be5a2bc06"), "StudentDetailsStudentName" : "John"}, { "$pull": {"StudentDetails$StudentSubjectDetails" : { "Marks":45 }} }, multi=true ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查文档-
> dbdeletingSpecificRecordDemofind()pretty();
这将产生以下文件-
{ "_id" : ObjectId("5cf2210ab64a577be5a2bc06"), "StudentDetails" : [ { "StudentName" : "John", "StudentSubjectDetails" : [ { "Subject" : "MySQL", "Marks" : 67 } ] } ] }