$pull 연산자를 사용하여 MongoDB의 배열에서 객체를 제거할 수 있습니다. 개념을 이해하기 위해 문서로 컬렉션을 만들어 보겠습니다. 문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다 -
> db.removeObjectFromArrayDemo.insertOne(
... {
...
... "StudentName": "John",
... "StudentAcademicProjectDetails":
... [{
... "StudentProjectId": 101,
... "StudentProjectName": "Pig Dice Game"
... },
... {
... "StudentProjectId": 110,
... "StudentProjectName": "Library Management System"
... },
...
... {
... "StudentProjectId": 120,
... "StudentProjectName": "Phonebook Management System"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ad13d6cea1f28b7aa0817")
} find() 메서드를 사용하여 컬렉션의 모든 문서를 표시합니다. 쿼리는 다음과 같습니다 -
> db.removeObjectFromArrayDemo.find().pretty();
다음은 출력입니다 -
{
"_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
"StudentName" : "John",
"StudentAcademicProjectDetails" : [
{
"StudentProjectId" : 101,
"StudentProjectName" : "Pig Dice Game"
},
{
"StudentProjectId" : 110,
"StudentProjectName" : "Library Management System"
},
{
"StudentProjectId" : 120,
"StudentProjectName" : "Phonebook Management System"
}
]
} 다음은 MongoDB의 배열에서 객체를 제거하는 쿼리입니다 -
> db.removeObjectFromArrayDemo.update(
... {'_id': ObjectId("5c8ad13d6cea1f28b7aa0817")},
... { $pull: { "StudentAcademicProjectDetails" : { StudentProjectId: 101 } } },
... false,
... true
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 컬렉션에서 문서를 확인하여 객체가 배열에서 제거되었는지 확인하겠습니다. 쿼리는 다음과 같습니다 -
> db.removeObjectFromArrayDemo.find().pretty();
다음은 출력입니다 -
{
"_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
"StudentName" : "John",
"StudentAcademicProjectDetails" : [
{
"StudentProjectId" : 110,
"StudentProjectName" : "Library Management System"
},
{
"StudentProjectId" : 120,
"StudentProjectName" : "Phonebook Management System"
}
]
} 위의 샘플 출력을 보면 101이 있는 "StudentProjectId" 필드가 제거되었습니다.