체인의정석

Document DB 에서 upsert 사용하기 본문

개발/database

Document DB 에서 upsert 사용하기

체인의정석 2025. 4. 17. 18:54
728x90

AWS에서는 자체적으로 mongoDB가 아닌 DocumentDB를 사용한다.

이에 따라 로컬에서는 발생하지 않던 에러가 AWS배포 시에 발생하였다.

Document DB에서 UPsert를 사용하니 "retryWrites" 관련 오류가 발생하였다.

https://docs.aws.amazon.com/documentdb/latest/developerguide/mongo-apis.html

 

Supported MongoDB APIs, operations, and data types in Amazon DocumentDB - Amazon DocumentDB

Supported MongoDB APIs, operations, and data types in Amazon DocumentDB Amazon DocumentDB (with MongoDB compatibility) is a fast, scalable, highly-available, and fully managed document database service that supports MongoDB workloads. Amazon DocumentDB is

docs.aws.amazon.com

하지만 찾아보니 Upsert는 DocumentDB에서 존재하는 것을 볼 수 있었다.
더 찾아보니 Document DB에서 사용할 때는

SetRetryWrites(false)

이와 같이 db 커넥션 단계에서 설정 값을 넣어주어야 한다고 한다.

if r.client, err = mongo.Connect(context.Background(), options.Client().ApplyURI(cfg["datasource"].(string)).SetAuth(credential).SetRetryWrites(false)); err != nil {

해당 설정 값을 넣어주게 되면 다음과 같은 upsert 문법 사용이 가능하다.

func (q *QuestDB) UpsertTest(test entity.Test) error {
	filter := bson.M{"id": info.ID}
	update := bson.M{
		"$set": bson.M{
			"name":               info.Name,
			"description":        info.Description,
			"updated_at":         time.Now(),
		},
		"$setOnInsert": bson.M{
			"created_at":  time.Now(),
		},
	}

	opts := options.Update().SetUpsert(true)

	_, err := q.collectionName.UpdateOne(context.TODO(), filter, update, opts)
	return err
}

이런식으로 serOnInsert에 created_at 및 최초 insert 시 넣을 값을 쓰고 set일 때는 업데이트 할 값을 사용하면 된다.

SetUpsert(true)해당 부분도 위의 설정 값이 없다면 오류가 나지만 있다면 오류가 나지 않게 된다.

728x90
반응형
Comments