본문 바로가기
프로그래머

MongoDB Sync 란 무엇인가? MongoDB Sync 사용 설명 및 사용 가이드, MongoDB Sync를 활용한 데이터 동기화 예제

by 정보경험 2025. 1. 23.
반응형

 

 

 

 

1. MongoDB Sync란 무엇인가?

MongoDB Sync는 클라이언트 애플리케이션과 MongoDB Atlas 간의 실시간 데이터 동기화를 지원하는 기술입니다. MongoDB Realm Sync라는 이름으로도 알려져 있으며, 로컬 데이터베이스와 클라우드 데이터베이스 간의 양방향 동기화를 자동화하여 개발자 경험을 간소화합니다.

2. MongoDB Sync 주요 구성 요소

구성 요소 설명
Realm SDK 클라이언트에서 로컬 데이터베이스를 관리하는 도구
MongoDB Atlas 클라우드에서 데이터베이스를 저장하고 관리하는 플랫폼
Sync Protocol 로컬 Realm과 MongoDB Atlas 간의 데이터 동기화 처리
Conflict Handler 동기화 중 충돌을 해결하는 자동 또는 사용자 정의 전략

3. MongoDB Sync 사용 방법

1) MongoDB Atlas 클러스터 생성

  1. MongoDB Atlas에 로그인하고 새 클러스터를 생성합니다.
  2. 데이터베이스 사용자 인증 정보를 설정합니다.
  3. IP 화이트리스트를 구성합니다.

 

 

 

 

2) Realm App 설정

  1. MongoDB Realm 콘솔에서 새 앱을 생성합니다.
  2. Sync를 활성화하고 동기화할 컬렉션과 규칙을 설정합니다.

3) 클라이언트 애플리케이션 통합

아래는 Node.js를 사용한 클라이언트 애플리케이션의 예제입니다:

const Realm = require("realm");

const app = new Realm.App({ id: "your-realm-app-id" });

async function run() {
    const credentials = Realm.Credentials.anonymous();
    const user = await app.logIn(credentials);

    const config = {
        schema: [{ name: "Task", properties: { name: "string", completed: "bool" } }],
        sync: {
            user,
            partitionValue: "myPartition",
        },
    };

    const realm = await Realm.open(config);

    realm.write(() => {
        realm.create("Task", { name: "Task 1", completed: false });
    });

    console.log("Data synced with MongoDB Atlas!");
}
run().catch(console.error);

4. MongoDB Sync 상태별  API  작업 관계도 

 

5. 주요 팁

  • Sync 활성화 시 데이터 충돌 가능성을 고려하여 Conflict Handler를 설정하세요.
  • 오프라인 기능이 중요한 애플리케이션에서는 Realm SDK를 최대한 활용하세요.
  • MongoDB Atlas의 클러스터 크기와 성능 설정을 적절히 조정하여 동기화 속도를 최적화하세요.

 

 

 

 

6. 자주 사용되는 사례

1) 채팅 애플리케이션

실시간 메시지 동기화를 통해 여러 사용자 간에 데이터를 동기화합니다.

 

설정 및 코드 예제

const Realm = require("realm");

const app = new Realm.App({ id: "your-realm-app-id" });

async function run() {
    const credentials = Realm.Credentials.anonymous();
    const user = await app.logIn(credentials);

    const config = {
        schema: [{
            name: "Message",
            properties: {
                sender: "string",
                content: "string",
                timestamp: "date"
            }
        }],
        sync: {
            user,
            partitionValue: "chat-room-1",
        },
    };

    const realm = await Realm.open(config);

    realm.write(() => {
        realm.create("Message", {
            sender: "User1",
            content: "Hello, World!",
            timestamp: new Date()
        });
    });

    console.log("Message synced!");
}
run().catch(console.error);

 

 

 

 

2) 오프라인 데이터 동기화

사용자가 오프라인 상태에서도 데이터를 사용하고, 네트워크가 복구되면 자동 동기화됩니다.

 

설정 및 코드 예제

const Realm = require("realm");

const app = new Realm.App({ id: "your-realm-app-id" });

async function run() {
    const credentials = Realm.Credentials.anonymous();
    const user = await app.logIn(credentials);

    const config = {
        schema: [{
            name: "OfflineData",
            properties: {
                key: "string",
                value: "string",
                updatedAt: "date"
            }
        }],
        sync: {
            user,
            partitionValue: "offline-partition",
        },
    };

    const realm = await Realm.open(config);

    realm.write(() => {
        realm.create("OfflineData", {
            key: "exampleKey",
            value: "exampleValue",
            updatedAt: new Date()
        });
    });

    console.log("Offline data synced when online!");
}
run().catch(console.error);

 

 

 

 

3) IoT 디바이스 관리

IoT 센서 데이터가 MongoDB Atlas에 자동으로 업로드되고 동기화됩니다.

 

설정 및 코드 예제

const Realm = require("realm");

const app = new Realm.App({ id: "your-realm-app-id" });

async function run() {
    const credentials = Realm.Credentials.anonymous();
    const user = await app.logIn(credentials);

    const config = {
        schema: [{
            name: "SensorData",
            properties: {
                deviceId: "string",
                temperature: "double",
                humidity: "double",
                timestamp: "date"
            }
        }],
        sync: {
            user,
            partitionValue: "iot-sensors",
        },
    };

    const realm = await Realm.open(config);

    realm.write(() => {
        realm.create("SensorData", {
            deviceId: "device001",
            temperature: 22.5,
            humidity: 60.3,
            timestamp: new Date()
        });
    });

    console.log("Sensor data synced with MongoDB Atlas!");
}
run().catch(console.error);
반응형