[MongoDB] Go Driver 사용법

배채윤·2020년 10월 26일
0

개요

우선 Go Driver가 BSON 객체를 어떻게 다루는지 이해하고 넘어가야한다. MongoDB의 document는 json 형태로 저장하는데, 이는 BSON(Binary-encoded Json)이라 불리는 바이너리 데이터로 인코딩되어 저장된다. 덕분에 MongoDB를 사용하는 어플리케이션들은 신뢰도 높은 process, sort, compare data 작업을 할 수 있다.

Go Driver는 BSON data를 나타내는 2가지 그룹군의 타입을 가지고 있다. D types와 Raw types다.
D Types는 native Go types로 간결하게 BSON Objects를 빌드할 수 있게 해준다. 특히 GO에서 MongoDB로 명령을 전달할 때 유용하다. D types은 아래 4가지 type들로 구성된다.

  • D: A BSON document. This type should be used in situations where order matters, such as MongoDB commands.
  • M: An unordered map. It is the same as D, except it does not preserve order.
  • A: A BSON array.
  • E: A single element inside a D.

일단 순서가 중요한 Document를 쿼리할 때는 D, 순서가 중요하지 않을 때는 M을 쓰면 된다는 사실만 잘 기억해두자.

사용법

Go Driver의 기본 사용법은 connection string에서 client를 생성하면서 시작된다.

  • client 생성 방법
client, err := NewClient(options.Client().ApplyURI("mongodb://foo:bar@localhost:27017"))
if err != nil { return err }
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil { return err }

여기서 context.WithTimeout은 client의 생명 주기를 제어하기 위해 사용된다. 즉, 데이터베이스 커넥션이 너무 길어지면 해당 커넥션을 종료해주는 역할을 한다는 것이다. Timeout을 사용하고 싶지 않다면 그냥 빈 context(context.Background())를 생성하여 전달해주면 된다.

  • collection 불러오기
collection := client.Database("baz").Collection("qux")

collection을 통해 DB와의 CRUD를 할 수 있다.
아래는 그 예다.

res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil { return err }
id := res.InsertedID

CREATE

InsertOne, InsertMany와 같은 함수를 통해 documen를 create 할 수 있다.

  • InsertOne
func (coll *Collection) InsertOne(ctx context.Context, document interface{},
    opts ...*options.InsertOneOptions) (*InsertOneResult, error)

collection에 document 하나를 insert 할 때 사용한다.

  • InsertMany
func (coll *Collection) InsertMany(ctx context.Context, documents []interface{},
    opts ...*options.InsertManyOptions) (*InsertManyResult, error)

READ

작성 중...

Reference

profile
새로운 기술을 테스트하고 적용해보는 걸 좋아하는 서버 개발자

0개의 댓글