在Ubuntu上實現MongoDB的數據持久化,主要涉及以下幾個步驟:
/etc/mongod.conf
中設置數據存儲路徑。默認情況下,數據存儲路徑通常為 /var/lib/mongodb
。確保該路徑有足夠的磁盤空間,且MongoDB進程有權限讀寫。const { MongoClient } = require('mongodb');
async function run() {
const client = new MongoClient('mongodb://localhost:27017', { writeConcern: { w: 'majority' } });
try {
await client.connect();
const database = client.db('myDatabase');
const collection = database.collection('myCollection');
const result = await collection.insertOne({ name: 'Alice' });
console.log('New listing created with the following id:', {result.insertedId});
} finally {
await client.close();
}
}
run().catch(console.dir);
mongodump
和 mongorestore
工具進行數據備份和恢復。建立定時任務(如使用 cron
)來定期執行備份操作,確保數據安全。通過以上步驟,你可以在Ubuntu上實現MongoDB的數據持久化,從而保護數據免受系統故障的影響。