node.js - 导出mongodb集合数据并使用node js导入回来

标签 node.js mongodb mongoose import export

我是 mongodb 的新手,所以需要一些关于使用 nodejs 导出和导入 mongodb 数据的帮助。我有一个 mongodb 数据库和一些集合(例如产品集合、公式集合和规则集合,其中包含产品 ID 的引用),我想根据 api 请求的参数从不同集合中导出数据,并生成包含相应数据的文件,该文件将在客户端浏览器上下载。用户可以使用导出的文件将导出的数据导入到另一个数据库实例中。已经搜索过此主题并找到了 this answer不确定我是否可以使用 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();
    });
});

关于node.js - 导出mongodb集合数据并使用node js导入回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63573995/

相关文章:

node.js - TypeError : this. add 不是 Node js应用程序中的函数

javascript - Sequelize 树中的连接数据

javascript - Monaco Editor 可动态调整大小

javascript - new ObjectId() 和 new ObjectId and ObjectId() 有什么区别?

python - 使用 Mongoengine 进行插入只能从 shell 工作,但不能从 Django View 工作

node.js - MongoDB Mongoose 模式设计

node.js - EC2 cron 作业未执行我的 Node.js 脚本

javascript - Sequelize 仅在子表中插入(关联 : belongsTo)

mongodb - 在 $lookup 之后将原始对象数组合并到 "as"字段中

node.js - 对 Mongoose 模型的虚拟属性进行 stub