JavaScript│Node js
Mongo DB 배열 안에 있는 필드 업데이트 하기
iIxmont
2019. 8. 8. 16:10
몽고 DB 에서 개별 필드를 업데이트 하는 것은 간단하다.
$rename 을 사용하거나 $set을 사용하면 된다.
https://docs.mongodb.com/manual/reference/operator/update/rename/index.html
$rename — MongoDB Manual
A collection students contains the following documents where a field nmae appears misspelled, i.e. should be name: The examples in this section successively updates the documents in the collection. Rename a Field in an Embedded Document To rename a field i
docs.mongodb.com
아래 코드는 배열 안에 있는 필드의 이름을 변경하는 코드다.
코드가 변경하는 데이터는 이렇게 생겼다.
await mongoClient.db('project').collection('projects').find({ "projectAttachments.created_at": { "$exists": true } }).forEach(function (doc) {
doc.projectAttachments.forEach(async function (projectAttachment) {
if (projectAttachment.hasOwnProperty("created_at")) { // 배열의 원소들이 해당 property를 가지고 있는가
var bulk = mongoClient.db('project').collection('projects').initializeOrderedBulkOp(); // 벌크 연산 준비
bulk.find({ "_id": doc._id, "projectAttachments.id": projectAttachment.id }).updateOne({
"$set": { "projectAttachments.$.createdAt": projectAttachment.created_at } // 왼쪽 필드 이름 : 바꿀려고 하는 이름 . 오른쪽 필드 이름 : 현재 필드 이름
});
bulk.find({ "_id": doc._id, "projectAttachments.id": projectAttachment.id }).updateOne({
"$unset": { "projectAttachments.$.created_at": 1 } // 기존 필드 제거
});
bulk.execute();
bulk = mongoClient.db('project').collection('projects').initializeOrderedBulkOp();
}
});
});
db에서 배열 아래 필드를 먼저 find 한다
$exists: true 로 있는지 확인한다.
bulk 변수를 선언한다.
bulk.find 를 통해서 bulk연산을 한다.
위쪽에 있는 $set으로 필드 이름을 변경한다.
아래 $unset은 기존 필드를 없앤다.