본문 바로가기
BE/MongoDB

Apps script MongoDB CRUD - Delete, Replace

by 벼락코드 2024. 9. 12.

Apps script MongoDB CRUD - Delete, Replace

이전 글에서 Create, Update에 대해서 알아보았다. Replace를 어디서 다룰까 하다가 좀 더 리스크가 큰 쪽에서 다루기로 결정했다. 이번 글에서는 apps script를 이용해 mongoDB상에 있는 document를 삭제하고 교체하는 방법에 대해 작성하였다.

 

 

1. 문서 삭제 (Delete)

문서삭제 함수명은 deleteDocumentInMongoDB()로 하였다.

endpoint의 말단 부분이 .../action/deleteOne임을 체크하자.

function deleteDocumentInMongoDB() {
  const apiKey = 'YOUR_API_KEY';
  const endpoint = 'https://data.mongodb-api.com/app/data-<app-id>/endpoint/data/v1/action/deleteOne';
  
  const payload = {
    dataSource: 'Cluster0',
    database: 'YourDatabase',
    collection: 'YourCollection',
    filter: { _id: { "$oid": "document_id_here" } }
  };

  const options = {
    method: 'post',
    contentType: 'application/json',
    headers: {
      'api-key': apiKey
    },
    payload: JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(endpoint, options);
  Logger.log(response.getContentText());
}

filter를 사용하는 방법이전 글에 작성해두었다. 

 

1-1. 삭제 테스트

스크립트를 작성하고 실행했을 때, 조건에 만족하는 것이 없으면 { "deleteCount" : 0 }이 출력된다.

따라서, 올바르게 삭제되었는지 확인을 하려면, 삭제하려는 도큐먼트의 개수가 몇 개인지 먼저 세어보아야 한다.

그래야 내가 지우려는 도큐먼트 갯수가 잘 지워졌는지 알 수 있다. 아래는 목표했던 1개 도큐먼트가 삭제되었을 때 출력된 실행 로그이다.

 

여기에 더하여 제대로 삭제되었는지는 mongoDB에서 2차적으로 확인을 해야한다. 나의 경우 잘 삭제되었다.

 

 

2. 문서 교체 (Replace)

update와 replace는 서로 매우 다르다. document를 교체하는 함수명은 replaceDocumentInMongoDB()로 하였다.

endpoint의 말단 부분도 ..../action/replaceOne 임을 체크하자.

function replaceDocumentInMongoDB() {
  const apiKey = 'YOUR_API_KEY';
  const endpoint = 'https://data.mongodb-api.com/app/data-<app-id>/endpoint/data/v1/action/replaceOne';
  
  const payload = {
    dataSource: 'Cluster0',
    database: 'YourDatabase',
    collection: 'YourCollection',
    filter: { _id: { "$oid": "document_id_here" } }, // Document ID to replace
    replacement: {
      field1: "new value",
      field2: "new value",
      // Add other fields you want to replace the document with
    }
  };

  const options = {
    method: 'post',
    contentType: 'application/json',
    headers: {
      'api-key': apiKey
    },
    payload: JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(endpoint, options);
  Logger.log(response.getContentText());
}