몽고DB 회사 소개¶
몽고DB - 문서 데이터베이스
Mongo의 DB는 소스 사용 가능한 크로스 플랫폼 문서 중심 데이터베이스 프로그램입니다. NoSQL 데이터베이스 프로그램으로 분류 된 MongoDB는 옵션 스키마와 JSON 같은 문서를 사용합니다.
본문 바로가기¶
- 설치
- 기본 명령
- 데이터베이스 운영
- Collection 운영
- 문서 작업
- 작업
- 인덱싱
- 중앙화 기구
- 데이터 모델링
- 신청
- 스윙
- 보안
- 백업 및 복원
- 기능 최적화
- 모니터링
- GridFS
- 변경 스트림
- 번역
- 모범 사례
설치하기¶
우분투 / 데비안¶
카지노사이트
CentOS/RHEL/페도라¶
카지노사이트
맥 OS¶
카지노사이트
윈도우¶
카지노사이트
기타 제품¶
카지노사이트
기본 명령¶
MongoDB에 연결¶
카지노사이트
기본 정보¶
카지노사이트
Shell 운영¶
카지노사이트
Database 운영¶
데이터베이스 제작 및 관리¶
카지노사이트
데이터베이스 관리¶
카지노사이트
회사소개¶
회사소개¶
ο 회원 관리
회사소개¶
카지노사이트
회사소개¶
카지노사이트
문서 작업¶
삽입 작업¶
카지노사이트
업데이트 작업¶
카지노사이트
작업 삭제¶
카지노사이트
찾기 및 수정 작업¶
카지노사이트
Query 작업¶
기본 쿼리¶
카지노사이트
Query 연산자¶
카지노사이트
고급 쿼리¶
오프화이트
텍스트 검색¶
카지노사이트
회사연혁¶
공지사항¶
오프화이트
관련 상품¶
카지노사이트
공지사항¶
카지노사이트
Aggregation 프레임¶
기본 설교¶
카지노사이트
의회 단계¶
카지노사이트
고급 집단¶
카지노사이트
협력업체¶
카지노사이트
데이터 모델링¶
문서 구조¶
```javascript // Embedded documents { _id: ObjectId("..."), name: "John Doe", email: "john@example.com", address: { street: "123 Main St", city: "New York", state: "NY", zipCode: "10001", country: "USA" }, phones: [ {type: "home", number: "555-1234"}, {type: "work", number: "555-5678"} ] }
// Referenced documents // User document { _id: ObjectId("507f1f77bcf86cd799439011"), name: "John Doe", email: "john@example.com" }
// Order document { _id: ObjectId("507f1f77bcf86cd799439012"), userId: ObjectId("507f1f77bcf86cd799439011"), orderDate: new Date(), items: [ {productId: ObjectId("..."), quantity: 2, price: 29.99}, {productId: ObjectId("..."), quantity: 1, price: 49.99} ], totalAmount: 109.97 } ```의 경우
Schema 디자인 패턴¶
```javascript // One-to-One: Embedded { _id: ObjectId("..."), name: "John Doe", profile: { bio: "Software developer", avatar: "avatar.jpg", preferences: { theme: "dark", language: "en" } } }
// One-to-Many: Embedded (small arrays) { _id: ObjectId("..."), title: "Blog Post", content: "...", comments: [ { author: "Alice", text: "Great post!", date: new Date() }, { author: "Bob", text: "Thanks for sharing", date: new Date() } ] }
// One-to-Many: Referenced (large arrays) // Blog post { _id: ObjectId("507f1f77bcf86cd799439011"), title: "Blog Post", content: "...", author: "John Doe" }
// Comments (separate collection) { _id: ObjectId("..."), postId: ObjectId("507f1f77bcf86cd799439011"), author: "Alice", text: "Great post!", date: new Date() }
// Many-to-Many: Array of references // User document { _id: ObjectId("507f1f77bcf86cd799439011"), name: "John Doe", skills: [ ObjectId("507f1f77bcf86cd799439021"), // JavaScript ObjectId("507f1f77bcf86cd799439022"), // MongoDB ObjectId("507f1f77bcf86cd799439023") // Node.js ] }
// Skill document { _id: ObjectId("507f1f77bcf86cd799439021"), name: "JavaScript", category: "Programming Language" }
// Polymorphic pattern { _id: ObjectId("..."), type: "vehicle", subtype: "car", make: "Toyota", model: "Camry", doors: 4, fuelType: "gasoline" }
{ _id: ObjectId("..."), type: "vehicle", subtype: "motorcycle", make: "Harley Davidson", model: "Street 750", engineSize: "750cc" } ```에 대하여
고급 패턴¶
```javascript // Bucket pattern (for time series data) { _id: ObjectId("..."), sensor_id: "sensor_001", timestamp: new Date("2023-01-01T00:00:00Z"), measurements: [ {time: new Date("2023-01-01T00:00:00Z"), temp: 20.5, humidity: 65}, {time: new Date("2023-01-01T00:01:00Z"), temp: 20.7, humidity: 64}, {time: new Date("2023-01-01T00:02:00Z"), temp: 20.6, humidity: 66} ], count: 3, min_temp: 20.5, max_temp: 20.7, avg_temp: 20.6 }
// Outlier pattern { _id: ObjectId("..."), product_id: "product_001", year: 2023, month: 1, sales: [ {day: 1, amount: 1000}, {day: 2, amount: 1200}, // ... normal days {day: 15, amount: 50000, note: "Black Friday sale"} // Outlier ] }
// Computed pattern { _id: ObjectId("..."), product_id: "product_001", reviews: [ {rating: 5, comment: "Excellent!"}, {rating: 4, comment: "Good product"}, {rating: 5, comment: "Love it!"} ], // Computed fields total_reviews: 3, average_rating: 4.67, rating_distribution: { 5: 2, 4: 1, 3: 0, 2: 0, 1: 0 } }
// Extended reference pattern { _id: ObjectId("..."), order_id: "ORD-001", customer: { id: ObjectId("507f1f77bcf86cd799439011"), name: "John Doe", email: "john@example.com" // Denormalized for quick access }, items: [ { product: { id: ObjectId("507f1f77bcf86cd799439021"), name: "Laptop", price: 999.99 // Denormalized }, quantity: 1 } ] } ```의 경우
이름 *¶
Replica 설정¶
```javascript // Initialize replica set rs.initiate({ _id: "myReplicaSet", members: [ {_id: 0, host: "mongodb1.example.com:27017"}, {_id: 1, host: "mongodb2.example.com:27017"}, {_id: 2, host: "mongodb3.example.com:27017"} ] })
// Add member to replica set rs.add("mongodb4.example.com:27017")
// Add member with options rs.add({ host: "mongodb4.example.com:27017", priority: 0.5, votes: 1 })
// Remove member from replica set rs.remove("mongodb4.example.com:27017")
// Check replica set status rs.status()
// Check replica set configuration rs.conf()
// Check if current node is primary rs.isMaster()
// Step down primary (force election) rs.stepDown(60) // Step down for 60 seconds
// Force reconfiguration rs.reconfig(config, {force: true}) ```에 대하여
Replica 설정 구성¶
```javascript // Configure replica set with different member types var config = { _id: "myReplicaSet", members: [ // Primary eligible members {_id: 0, host: "mongodb1.example.com:27017", priority: 2}, {_id: 1, host: "mongodb2.example.com:27017", priority: 1},
// Secondary only (priority 0)
{_id: 2, host: "mongodb3.example.com:27017", priority: 0},
// Hidden member (for backups)
{_id: 3, host: "mongodb4.example.com:27017", priority: 0, hidden: true},
// Arbiter (voting only, no data)
{_id: 4, host: "mongodb5.example.com:27017", arbiterOnly: true},
// Delayed member (for point-in-time recovery)
{_id: 5, host: "mongodb6.example.com:27017", priority: 0, slaveDelay: 3600}
] }
rs.initiate(config)
// Modify replica set configuration var config = rs.conf() config.members[0].priority = 3 rs.reconfig(config)
// Set read preference db.getMongo().setReadPref("secondary") db.getMongo().setReadPref("primaryPreferred") db.getMongo().setReadPref("secondaryPreferred")
// Read from specific tag db.getMongo().setReadPref("secondary", [{datacenter: "west"}]) ```의 경우
모니터링¶
카지노사이트
인기 카테고리¶
Shard 클러스터 설정¶
카지노사이트
Shards 관리¶
카지노사이트
Shard 키 선택¶
카지노사이트
계정 관리¶
인증현황¶
카지노사이트
인증 및 역할¶
카지노사이트
사이트맵 제품 설명¶
```bash
Generate SSL certificates¶
openssl req -newkey rsa:2048 -new -x509 -days 3653 -nodes -out mongodb-cert.crt -keyout mongodb-cert.key
Combine certificate and key¶
cat mongodb-cert.key mongodb-cert.crt > mongodb.pem
Start MongoDB with SSL¶
mongod --sslMode requireSSL --sslPEMKeyFile /path/to/mongodb.pem
Connect with SSL¶
mongosh --ssl --sslCAFile /path/to/ca.pem --host hostname
MongoDB configuration file (mongod.conf)¶
net: ssl: mode: requireSSL PEMKeyFile: /path/to/mongodb.pem CAFile: /path/to/ca.pem ```의 경우
Field-Level 암호화¶
```javascript // Client-side field level encryption setup const { MongoClient, ClientEncryption } = require('mongodb');
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, autoEncryption: { keyVaultNamespace: 'encryption.__keyVault', kmsProviders: { local: { key: localMasterKey } }, schemaMap: { 'myDatabase.users': { bsonType: 'object', properties: { ssn: { encrypt: { keyId: dataKeyId, bsonType: 'string', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' } }, creditCard: { encrypt: { keyId: dataKeyId, bsonType: 'string', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Random' } } } } } } });
// Create data encryption key const encryption = new ClientEncryption(client, { keyVaultNamespace: 'encryption.__keyVault', kmsProviders: { local: { key: localMasterKey } } });
const dataKeyId = await encryption.createDataKey('local');
// Insert encrypted document await db.users.insertOne({ name: 'John Doe', ssn: '123-45-6789', // Will be encrypted creditCard: '4111-1111-1111-1111' // Will be encrypted }); ```의 경우
감사합니다.¶
카지노사이트
백업 및 복원¶
mongodump 과 mongorestore¶
```bash
Backup entire MongoDB instance¶
mongodump --host localhost:27017 --out /backup/mongodb
Backup specific database¶
mongodump --host localhost:27017 --db myDatabase --out /backup/mongodb
Backup specific collection¶
mongodump --host localhost:27017 --db myDatabase --collection users --out /backup/mongodb
Backup with authentication¶
mongodump --host localhost:27017 --username admin --password --authenticationDatabase admin --out /backup/mongodb
Backup with query filter¶
mongodump --host localhost:27017 --db myDatabase --collection users --query '{"status": "active"}' --out /backup/mongodb
Backup in archive format¶
mongodump --host localhost:27017 --db myDatabase --archive=/backup/myDatabase.archive
Backup with compression¶
mongodump --host localhost:27017 --db myDatabase --gzip --out /backup/mongodb
Restore entire backup¶
mongorestore --host localhost:27017 /backup/mongodb
Restore specific database¶
mongorestore --host localhost:27017 --db myDatabase /backup/mongodb/myDatabase
Restore to different database¶
mongorestore --host localhost:27017 --db newDatabase /backup/mongodb/myDatabase
Restore specific collection¶
mongorestore --host localhost:27017 --db myDatabase --collection users /backup/mongodb/myDatabase/users.bson
Restore with drop existing¶
mongorestore --host localhost:27017 --drop /backup/mongodb
Restore from archive¶
mongorestore --host localhost:27017 --archive=/backup/myDatabase.archive
Restore with authentication¶
mongorestore --host localhost:27017 --username admin --password --authenticationDatabase admin /backup/mongodb ```의 경우
Filesystem 스냅샷¶
```bash
Stop MongoDB (for consistent snapshot)¶
sudo systemctl stop mongod
Create filesystem snapshot (LVM example)¶
sudo lvcreate --size 1G --snapshot --name mongodb-snapshot /dev/vg0/mongodb-lv
Start MongoDB¶
sudo systemctl start mongod
Mount snapshot¶
sudo mkdir /mnt/mongodb-snapshot sudo mount /dev/vg0/mongodb-snapshot /mnt/mongodb-snapshot
Copy data from snapshot¶
sudo cp -r /mnt/mongodb-snapshot/data /backup/mongodb-snapshot-$(date +%Y%m%d)
Unmount and remove snapshot¶
sudo umount /mnt/mongodb-snapshot sudo lvremove /dev/vg0/mongodb-snapshot
For replica sets (no downtime required)¶
Take snapshot from secondary member¶
Ensure secondary is caught up before snapshot¶
```를 호출합니다.
클라우드 백업 솔루션¶
```bash
MongoDB Atlas automated backups¶
- Continuous backups with point-in-time recovery¶
- Scheduled snapshot backups¶
- Cross-region backup copies¶
AWS backup using EBS snapshots¶
aws ec2 create-snapshot --volume-id vol-1234567890abcdef0 --description "MongoDB backup $(date)"
Google Cloud backup using persistent disk snapshots¶
gcloud compute disks snapshot mongodb-disk --snapshot-names=mongodb-backup-$(date +%Y%m%d)
Azure backup using managed disk snapshots¶
az snapshot create --resource-group myResourceGroup --source mongodb-disk --name mongodb-backup-$(date +%Y%m%d) ```의 경우
자동화된 백업 스크립트¶
```bash
!/bin/bash¶
mongodb_backup.sh¶
Configuration¶
MONGO_HOST="localhost:27017" MONGO_USER="backup_user" MONGO_PASS="backup_password" BACKUP_DIR="/backup/mongodb" RETENTION_DAYS=7 DATE=$(date +%Y%m%d_%H%M%S)
Create backup directory¶
mkdir -p \(BACKUP_DIR/\)DATE
Perform backup¶
mongodump --host $MONGO_HOST \ --username $MONGO_USER \ --password $MONGO_PASS \ --authenticationDatabase admin \ --gzip \ --out \(BACKUP_DIR/\)DATE
Check backup success¶
if [ $? -eq 0 ]; then echo "Backup completed successfully: \(BACKUP_DIR/\)DATE"
# Compress backup tar -czf \(BACKUP_DIR/mongodb_backup_\)DATE.tar.gz -C $BACKUP_DIR $DATE rm -rf \(BACKUP_DIR/\)DATE
# Upload to cloud storage (optional) # aws s3 cp \(BACKUP_DIR/mongodb_backup_\)DATE.tar.gz s3://my-backup-bucket/
# Clean old backups find \(BACKUP_DIR -name "mongodb_backup_*.tar.gz" -mtime +\)RETENTION_DAYS -delete
else echo "Backup failed!" exit 1 fi
Add to crontab for daily backups¶
0 2 * * * /path/to/mongodb_backup.sh >> /var/log/mongodb_backup.log 2>&1¶
```로
성능 최적화¶
Query 최적화¶
카지노사이트
Index 최적화¶
오프화이트
연결 최적화¶
카지노사이트
메모리 및 스토리지 최적화¶
__CODE_BLOCK_49_로그
관련 기사¶
Database 모니터링¶
카지노사이트
성능 미터¶
```javascript // Query performance monitoring var slowQueries = db.system.profile.find({ millis: {$gt: 1000} }).sort({ts: -1}).limit(10)
slowQueries.forEach(function(query) { print("Duration: " + query.millis + "ms") print("Command: " + JSON.stringify(query.command)) print("---") })
// Index effectiveness db.users.find({email: "john@example.com"}).explain("executionStats").executionStats
// Memory usage var memStats = db.serverStatus().mem print("Resident: " + memStats.resident + "MB") print("Virtual: " + memStats.virtual + "MB") print("Mapped: " + memStats.mapped + "MB")
// WiredTiger cache statistics var cacheStats = db.serverStatus().wiredTiger.cache print("Cache size: " + cacheStats["maximum bytes configured"] / 1024 / 1024 + "MB") print("Cache used: " + cacheStats["bytes currently in the cache"] / 1024 / 1024 + "MB")
// Network statistics var networkStats = db.serverStatus().network print("Bytes in: " + networkStats.bytesIn) print("Bytes out: " + networkStats.bytesOut) print("Requests: " + networkStats.numRequests)
// Lock statistics db.serverStatus().locks
// Background flushing db.serverStatus().backgroundFlushing ```를 호출합니다.
모니터링 스크립트¶
```bash
!/bin/bash¶
mongodb_monitor.sh¶
MONGO_HOST="localhost:27017" MONGO_USER="monitor" MONGO_PASS="password"
Check if MongoDB is running¶
if ! mongosh --host $MONGO_HOST --username $MONGO_USER --password $MONGO_PASS --eval "db.runCommand('ping')" > /dev/null 2>&1; then echo "ERROR: MongoDB is not responding" exit 1 fi
Check replication lag¶
LAG=$(mongosh --host $MONGO_HOST --username $MONGO_USER --password $MONGO_PASS --quiet --eval " if (rs.status().ok) { var lag = rs.status().members.find(m => m.self).optimeDate - rs.status().members.find(m => m.state === 1).optimeDate; print(Math.abs(lag)); } else { print(0); } ")
if [ $LAG -gt 10000 ]; then echo "WARNING: Replication lag is ${LAG}ms" fi
Check slow queries¶
SLOW_QUERIES=$(mongosh --host $MONGO_HOST --username $MONGO_USER --password $MONGO_PASS --quiet --eval " db.system.profile.countDocuments({millis: {$gt: 1000}, ts: {$gt: new Date(Date.now() - 300000)}}) ")
if [ $SLOW_QUERIES -gt 10 ]; then echo "WARNING: $SLOW_QUERIES slow queries in last 5 minutes" fi
Check connections¶
CONNECTIONS=$(mongosh --host $MONGO_HOST --username $MONGO_USER --password $MONGO_PASS --quiet --eval " db.serverStatus().connections.current ")
if [ $CONNECTIONS -gt 800 ]; then echo "WARNING: High connection count: $CONNECTIONS" fi
echo "MongoDB monitoring completed at $(date)" ```의 경우
Third-Party 모니터링 도구¶
카지노사이트
그리드FS¶
GridFS 기초¶
카지노사이트
Node.js를 가진 GridFS¶
```javascript const { MongoClient, GridFSBucket } = require('mongodb');
async function gridfsExample() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect();
const db = client.db('myDatabase'); const bucket = new GridFSBucket(db, { bucketName: 'uploads' });
// Upload file const fs = require('fs'); const uploadStream = bucket.openUploadStream('example.pdf', { metadata: { userId: 'user123', uploadDate: new Date(), contentType: 'application/pdf' } });
fs.createReadStream('/path/to/file.pdf').pipe(uploadStream);
uploadStream.on('finish', () => { console.log('File uploaded successfully'); });
// Download file const downloadStream = bucket.openDownloadStreamByName('example.pdf'); downloadStream.pipe(fs.createWriteStream('/path/to/downloaded.pdf'));
// Find files const files = await bucket.find({ 'metadata.userId': 'user123' }).toArray(); console.log(files);
// Delete file await bucket.delete(fileId);
await client.close(); } ```로
GridFS 관리¶
카지노사이트
변화 Streams¶
기본 변경 스트림¶
카지노사이트
고급 변경 스트림¶
카지노사이트
응용 프로그램¶
```javascript // Node.js example with change streams const { MongoClient } = require('mongodb');
async function watchChanges() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect();
const db = client.db('myDatabase'); const collection = db.collection('users');
// Watch for user status changes const changeStream = collection.watch([ { $match: { $and: [ { operationType: 'update' }, { 'updateDescription.updatedFields.status': { $exists: true } } ] } } ], { fullDocument: 'updateLookup' });
changeStream.on('change', async (change) => { const { documentKey, fullDocument, updateDescription } = change;
console.log(`User ${documentKey._id} status changed to ${fullDocument.status}`);
// Trigger business logic based on status change
if (fullDocument.status === 'premium') {
await sendWelcomeEmail(fullDocument.email);
} else if (fullDocument.status === 'inactive') {
await scheduleAccountCleanup(documentKey._id);
}
});
// Handle errors and reconnection changeStream.on('error', (error) => { console.error('Change stream error:', error); setTimeout(() => { watchChanges(); // Restart change stream }, 5000); }); }
// Real-time notifications async function setupNotifications() { const changeStream = db.notifications.watch([ { $match: { operationType: 'insert', 'fullDocument.userId': currentUserId } } ]);
changeStream.on('change', (change) => { const notification = change.fullDocument; // Send to WebSocket client websocket.send(JSON.stringify({ type: 'notification', data: notification })); }); } ```에
계정 관리¶
단일 문서 거래¶
```javascript // MongoDB provides atomicity for single document operations // These are automatically atomic:
db.users.updateOne( { _id: ObjectId("507f1f77bcf86cd799439011") }, { $inc: { balance: -100 }, $push: { transactions: { type: "debit", amount: 100, date: new Date() } } } )
// findAndModify operations are also atomic db.users.findOneAndUpdate( { _id: ObjectId("507f1f77bcf86cd799439011") }, { $inc: { balance: -100 } }, { returnDocument: "after" } ) ```의 경우
Multi-Document 거래¶
카지노사이트
Node.js와 거래¶
카지노사이트
거래 모범 사례¶
```javascript // Keep transactions short // Bad: Long-running transaction session.startTransaction(); // ... many operations // ... external API calls // ... complex calculations session.commitTransaction();
// Good: Short transaction session.startTransaction(); // Only essential database operations session.commitTransaction();
// Use appropriate read/write concerns session.startTransaction({ readConcern: { level: 'majority' }, writeConcern: { w: 'majority', j: true } });
// Handle transaction conflicts async function retryTransaction(operation, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { await operation(); return; } catch (error) { if (error.hasErrorLabel('TransientTransactionError') && i < maxRetries - 1) { console.log('Retrying transaction...'); continue; } throw error; } } }
// Avoid hotspots in sharded clusters // Use well-distributed shard keys for transactional collections
// Monitor transaction performance db.serverStatus().transactions ```의 경우
최고의 연습¶
Schema 디자인 모범 사례¶
카지노사이트
성과 모범 사례¶
카지노사이트
보안 모범 사례¶
카지노사이트
운영 모범 사례¶
카지노사이트
개발 모범 사례¶
카지노사이트
제품정보¶
Mongo의 DB는 다양한 데이터 유형과 스케일링을 수평으로 처리하는 강력한 유연한 NoSQL 문서 데이터베이스입니다. 이 포괄적인 속임수 덮개 근본적인 Mongo 기본 CRUD의 DB 운영은 sharding, Transaction 및 Performance Optimization과 같은 고급 주제로 구성됩니다.
** 키 강도:** - Flexible Schema: 동적 스키마를 가진 JSON 같은 문서 - Horizontal Scaling: 분산 배포를 위한 내장 스윙 - Rich Query Language **: 강력한 집계 프레임 워크 및 색인 - **높은 가용성 **: 자동적인 고장을 가진 Replica 세트 - **Developer Friendly: 직관적인 문서 모델과 광범위한 드라이버 지원
** 최고의 사용 사례:** - 콘텐츠 관리 시스템 및 카탈로그 - 실시간 분석 및 IoT 애플리케이션 - 모바일 및 소셜 응용 - 제품 카탈로그 및 재고 관리 - 급속한 발달 및 iteration를 요구하는 신청
** 중요 고려 사항 : ** - Proper schema 디자인은 성능에 중요합니다. - Index 전략은 쿼리 패턴과 일치해야 합니다. - 일반 모니터링 및 유지 보수는 필수 - 백업 및 재난 복구 절차는 시험되어야 합니다 - 보안 구성은 주의를 기울여야 합니다.
이 속임수 시트에 명시된 관행과 기법을 따르면 효과적으로 설계, 구현 및 MongoDB 데이터베이스를 안전하게 유지하고, 수행하고, 모든 응용 프로그램 요구 사항에 대해 확장 할 수 있습니다.
<문서> 기능 copyToClipboard () 이름 * const 명령어 = document.querySelectorAll('code'); let allCommands = ''; 명령. forEach(cmd =>의 경우 모든Commands +=cmd.textContent + navigator.clipboard.write텍스(allCommands); alert('모든 명령은 클립보드에 복사!'); 이름 *
함수 생성PDF() { 창. 인쇄 (); 이름 *