접두사 문자열이 있는 배열의 모든 요소를 업데이트하려면 forEach()를 사용합니다. 먼저 문서로 컬렉션을 생성해 보겠습니다. −
> db.replaceAllElementsWithPrefixDemo.insertOne(
{
"StudentNames" : [
"John",
"Carol"
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd91908b50a6c6dd317ad8e")
}
>
>
> db.replaceAllElementsWithPrefixDemo.insertOne(
{
"StudentNames" : [
"Sam"
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd9191cb50a6c6dd317ad8f")
} 다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다. -
> db.replaceAllElementsWithPrefixDemo.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : ObjectId("5cd91908b50a6c6dd317ad8e"),
"StudentNames" : [
"John",
"Carol"
]
}
{
"_id" : ObjectId("5cd9191cb50a6c6dd317ad8f"),
"StudentNames" : [
"Sam"
]
} 다음은 배열의 모든 요소를 접두사 문자열로 바꾸는 쿼리입니다. 접두사 문자열은 "MR"입니다 -
> db.replaceAllElementsWithPrefixDemo.find().forEach(function (myDocumentValue) {
var prefixValue = myDocumentValue.StudentNames.map(function (myValue) {
return "MR." + myValue;
});
db.replaceAllElementsWithPrefixDemo.update(
{_id: myDocumentValue._id},
{$set: {StudentNames: prefixValue}}
);
}); 문서를 다시 한 번 확인합시다 -
> db.replaceAllElementsWithPrefixDemo.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : ObjectId("5cd91908b50a6c6dd317ad8e"),
"StudentNames" : [
"MR.John",
"MR.Carol"
]
}
{
"_id" : ObjectId("5cd9191cb50a6c6dd317ad8f"),
"StudentNames" : [
"MR.Sam"
]
}