> For the complete documentation index, see [llms.txt](https://koonkim.gitbook.io/mongodb/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://koonkim.gitbook.io/mongodb/master/undefined/replication/setup.md).

# Setup

Setting up about MongoDB Replication

![Client Driver와 Replication 이 동작하는 환경](https://2913574495-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lb7Vg1sUEHzMkgFpUvH%2F-LiGPHKMvMeCImeeB2Ji%2F-LiGQvW9JVmsPCOUo4-t%2Freplication.png?alt=media\&token=a2ffbafe-e4a1-4d61-b30f-69e7b5077c87)

총  3대의 MongoDB 인스턴스로 구성된  Replication 을 구성해보는 실습으로, 3대의 머신에서 하고 싶지만, 환경적인 제약이 많이 따르기 때문에 1대의 컴퓨터에서 진행하도록 하겠다. 위의 Replication set을 구성해보도록 하겠다.

본 예시에서 사용하는 replica set의 이름은 `replica-set` 으로 하고,  replication에 속해있는 node 의 이름으로써, Primary: `primary`, Secondary: `secondary-1`, `secondary-2`로 진행하겠다.

하나의 머신에서 진행되기 때문에 port를 바꾸는 방식으로 진행하겠음. 만약 다수의 노드에서 하고 싶다면 폴더를 노드라고 생각해도 무방하다. 예를 들어, shard1을 node1, shard2를 node2라고 생각해도 좋다.

* /path/to/mongodb/primary : the folder to store data in primary node
* /path/to/mongodb/secondary-1 : the folder to store data in first replication node
* /path/to/mongodb/secondary-2 : the folder to store data in second replication node

##

##

##

## Test

mongos에 접근하여서 아래의 내용을 작성해 본다. 100,000개를 insert해서 각 shard에 데이터가 분산되어 있는지 확인하는 작업이다.

현재 sharding은 range와 hash 두가지를 지원하는데 우리는 hash 방법으로 데이터를 분산해 보자.

```
> sh.enableSharding("shardingTest")
> use shardingTest
> db.items.createIndex({"index": "hashed"})
> sh.shardCollection("shardingTest.items", {"index": "hashed"})
> for (var n=1; n<=100000; n++)
>  db.items.insert({index: n, name: "test"})
> db.items.count() // print 100,000
```

마지막 줄 (line 7)에서 실제로 insert가 확실히 되었는지 확인을 해보자.

다음으로는 각 mongod 서버에 접근하여 그 노드에 데이터의 개수로 잘 분산 되어 있는지 확인해 본다.

```
// connect primary shard server
> use shardingTest
> db.items.count() // print about 30,000 each server
```

mongos에서 db를 만들고 insert를 했기 때문에 약 3만개씩 분배되어 있을 것이다.&#x20;

hash로 분배되어 있기 때문에 정확한 3으로 나뉜 개수로 분배되지는 않지만 대략적으로 3만개씩 분산되어 있는것을 확인할 수 있을 것이다.
