Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

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
            }
         ]
      }
   ]
}