특정 배열 인덱스의 객체를 업데이트하려면 MongoDB에서 update()를 사용하십시오. 먼저 문서로 컬렉션을 생성해 보겠습니다. −
> db.updateObjectDemo.insertOne(
... {
... id : 101,
... "StudentDetails":
... [
... [
... {
... "StudentName": "John"
... },
... { "StudentName": "Chris" }
... ],
... [ { "StudentName": "Carol" },
... { "StudentName": "David" } ]
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccdcd9b685b30d09a7111e0")
} 다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다. -
> db.updateObjectDemo.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : ObjectId("5ccdcd9b685b30d09a7111e0"),
"id" : 101,
"StudentDetails" : [
[
{
"StudentName" : "John"
},
{
"StudentName" : "Chris"
}
],
[
{
"StudentName" : "Carol"
},
{
"StudentName" : "David"
}
]
]
} 다음은 MongoDB의 특정 배열 인덱스에서 개체를 업데이트하는 쿼리입니다 -
> db.updateObjectDemo.update({"id":101},{$set:{"StudentDetails.1.1.StudentName":"Mike"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 특정 인덱스 [1,1]에 있는 객체를 확인해보자. "David" 값이 업데이트되었는지 여부 -
> db.updateObjectDemo.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : ObjectId("5ccdcd9b685b30d09a7111e0"),
"id" : 101,
"StudentDetails" : [
[
{
"StudentName" : "John"
},
{
"StudentName" : "Chris"
}
],
[
{
"StudentName" : "Carol"
},
{
"StudentName" : "Mike"
}
]
]
}