在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的数据持久化,从而保护数据免受系统故障的影响。