确保Linux上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
)来定期执行备份操作,确保数据安全。# 示例备份脚本
#!/bin/sh
mysqldump -u root -p mydatabase > /backups/mongodb_backup_$(date +%F).sql
通过以上步骤,可以有效地确保Linux上MongoDB数据的持久化,从而保护数据免受系统故障的影响。