导出mongodb集合数据,然后使用节点js

问题描述

我是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();
    });
});