MongoDB의 기존 레코드를 제거하고 업데이트하는 $pull 연산자만 사용할 수 있습니다. 먼저 문서로 컬렉션을 만들어 보겠습니다. −
> db.removeDemo.insertOne(
... {
... "UserName" : "Larry",
... "UserDetails" : [
... {
... "_id" : 101,
... "UserEmailId" : "976Larry@gmail.com",
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f9f88f9e6ff3eb0ce446")
}
> db.removeDemo.insertOne(
... {
... "UserName" : "Mike",
... "UserDetails" : [
... {
... "_id" : 102,
... "UserEmailId" : "Mike121@gmail.com",
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f9f98f9e6ff3eb0ce447")
} 다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다. -
> db.removeDemo.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"),
"UserName" : "Larry",
"UserDetails" : [
{
"_id" : 101,
"UserEmailId" : "976Larry@gmail.com"
}
]
}
{
"_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"),
"UserName" : "Mike",
"UserDetails" : [
{
"_id" : 102,
"UserEmailId" : "Mike121@gmail.com"
}
]
} 이제 기존 레코드를 제거하고 업데이트하기 위해 $pull 쿼리를 구현해 보겠습니다. -
> db.removeDemo.update(
... {"_id": ObjectId("5cc7f9f98f9e6ff3eb0ce447")},
... { "$pull": { "UserDetails": {"_id": 102}}}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 개체가 제거되었는지 확인하기 위해 컬렉션의 문서를 표시해 보겠습니다. -
> db.removeDemo.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"),
"UserName" : "Larry",
"UserDetails" : [
{
"_id" : 101,
"UserEmailId" : "976Larry@gmail.com"
}
]
}
{
"_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"),
"UserName" : "Mike",
"UserDetails" : [ ]
}