node.js - 导出 mongodb 集合数据并使用 node js 将其导入回来
问题描述
我是 mongodb 的新手,所以在使用 nodejs 导出和导入 mongodb 数据方面需要一些帮助。我有一个 mongodb 数据库和一些集合(例如产品集合、公式集合和规则集合,其中有产品 id 的引用),我想根据 api 请求的参数从不同的集合中导出数据,并生成包含相应数据的文件,该文件将下载到客户端浏览器上。用户可以使用导出的文件将导出的数据导入另一个数据库实例。已经在这个主题上进行了搜索并且遇到了这个答案,不确定我是否可以使用 mongoexport 来完成我的任务。知道我该怎么做。非常感谢任何帮助或想法。提前致谢。
解决方案
此代码将从 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();
});
});
推荐阅读
- sql - Impala SQL 查询与 1 个表并发现与 3 个主机名相同
- android - 没有找到类“android.support.constraint.Barrier”
- r - 如何按因子更改ggplot(R)中的背景?
- java - 如何用 Lombok Date And Collections 定义不可变?
- linux - 如何将文件夹从linux机器转移到windows
- android - Android Studio 附加到进程未找到本机符号
- python - python 3.6 和更早版本与 3.7 中不可变对象的“is”行为不一致
- python - Pandas:根据特定列值重置增量
- javascript - 循环遍历一个javascript数组将值添加到另一个数组
- rabbitmq - 如何使用 Apache Camel 在 RabbitMQ 消息上设置自定义标头?