배열 내의 문서를 삭제하려면 $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"
}
]
} 위의 샘플 출력을 보면 값이 5인 "StudentId", 즉 StudentName "David"가 삭제되었습니다.