MongoDB의 배열에서 객체를 제거하려면 $pull 연산자를 사용할 수 있습니다. 구문은 다음과 같습니다.
db.yourCollectionName.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
{$pull:{"yourArrayName":{"yourArrayFieldName":yourValue}}},
false,true); 위의 구문을 이해하기 위해 document를 사용하여 컬렉션을 생성해 보겠습니다. 문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다.
> db.removeObject.insertOne({"CustomerName":"Maxwell","CustomerAge":23,
... "CustomerDetails":[
... {
... "CustomerId":100,
... "CustomerProduct":"Product-1"
... },
... {
... "CustomerId":150,
... "CustomerProduct":"Product-2"
... },
... {
... "CustomerId":200,
... "CustomerProduct":"Product-3"
... }
... ]
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ea036a0c51185aefbd14f")
} find() 메서드를 사용하여 컬렉션의 모든 문서를 표시합니다. 쿼리는 다음과 같습니다.
> db.removeObject.find().pretty();
다음은 출력입니다.
{
"_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
"CustomerName" : "Maxwell",
"CustomerAge" : 23,
"CustomerDetails" : [
{
"CustomerId" : 100,
"CustomerProduct" : "Product-1"
},
{
"CustomerId" : 150,
"CustomerProduct" : "Product-2"
},
{
"CustomerId" : 200,
"CustomerProduct" : "Product-3"
}
]
} 다음은 MongoDB의 배열에서 객체를 제거하는 쿼리입니다.
> db.removeObject.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
... {$pull:{"CustomerDetails":{"CustomerId":150}}},
... false,true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 위에서 우리는 배열에서 객체를 제거했습니다. 컬렉션의 문서를 표시해 보겠습니다. 쿼리는 다음과 같습니다.
> db.removeObject.find().pretty();
다음은 출력입니다.
{
"_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
"CustomerName" : "Maxwell",
"CustomerAge" : 23,
"CustomerDetails" : [
{
"CustomerId" : 100,
"CustomerProduct" : "Product-1"
},
{
"CustomerId" : 200,
"CustomerProduct" : "Product-3"
}
]
}