此代码将从 MongoDB 集合(导出功能)中读取文档,然后以 JSON 格式写入文件。此文件用于读取(导入功能)并将 JSON 插入另一个集合。代码使用MongoDB NodeJS驱动。
出口:
根据提供的查询从集合 inCollection 中读取,并以 JSON“out_file.json”的形式写入文件。
const MongoClient = require('mongodb').MongoClient;
const fs = require('fs');
const dbName = 'testDB';
const client = new MongoClient('mongodb://localhost:27017', { useUnifiedTopology:true });
client.connect(function(err) {
//assert.equal(null, err);
console.log('Connected successfully to server');
const db = client.db(dbName);
getDocuments(db, function(docs) {
console.log('Closing connection.');
client.close();
// Write to file
try {
fs.writeFileSync('out_file.json', JSON.stringify(docs));
console.log('Done writing to file.');
}
catch(err) {
console.log('Error writing to file', err)
}
});
}
const getDocuments = function(db, callback) {
const query = { }; // this is your query criteria
db.collection("inCollection")
.find(query)
.toArray(function(err, result) {
if (err) throw err;
callback(result);
});
};
导入:
读取导出的“out_file.json”文件并将 JSON 数据插入到outCollection。
client.connect(function(err) {
const db = client.db(dbName);
const data = fs.readFileSync('out_file.json');
const docs = JSON.parse(data.toString());
db.collection('outCollection')
.insertMany(docs, function(err, result) {
if (err) throw err;
console.log('Inserted docs:', result.insertedCount);
client.close();
});
});