MongoDB에서 update()를 사용하여 배열 개체를 업데이트합니다. 점 표기법의 사용도 필요합니다. 문서로 컬렉션을 만들자 −
> db.demo489.insertOne(
... {
...
...
... details : [{
... id : 101,
... "Info1" : {
... "StudentName" : "Chris"
... },
... "Info2" : {
... "TeacherName" : "David"
... }
... },
... {
... id : 102,
... "Info1" : {
... "StudentName" : "Carol"
... },
... "Info2" : {
... "TeacherName" : "Mike"
... }
... }
...
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8356e0b0f3fa88e22790ba")
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo489.find();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e8356e0b0f3fa88e22790ba"), "details" : [ { "id" : 101, "Info1" : {
"StudentName" : "Chris" }, "Info2" : { "TeacherName" : "David" } }, { "id" : 102, "Info1" : {
"StudentName" : "Carol" }, "Info2" : { "TeacherName" : "Mike" } } ] } 다음은 배열 객체를 업데이트하는 쿼리입니다 -
> db.demo489.update({"details.id":102},
... {$set: {"details.$.Info1.StudentName":"Robert",
... "details.$.Info2.TeacherName":"John",
... "details.$.CountryName" : "US"
...
... }
... })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo489.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : ObjectId("5e8356e0b0f3fa88e22790ba"),
"details" : [
{
"id" : 101,
"Info1" : {
"StudentName" : "Chris"
},
"Info2" : {
"TeacherName" : "David"
}
},
{
"id" : 102,
"Info1" : {
"StudentName" : "Robert"
},
"Info2" : {
"TeacherName" : "John"
},
"CountryName" : "US"
}
]
}