使用Node.js导出MongoDB集合数据并重新导入

4

我是mongodb的新手,需要在nodejs中导入和导出mongodb数据的帮助。我的mongodb数据库中有一些集合(例如产品集合、公式集合和具有产品ID引用的规则集合),我想基于API请求的参数从不同的集合中导出数据,并生成包含相应数据的文件,该文件将被下载到客户端浏览器上。导出的文件可以被用户用来将导出的数据导入另一个数据库实例中。我已经搜索过这个主题,并找到了这篇答案,但不确定是否可以使用mongoexport来完成我的任务。有什么想法或帮助都将不胜感激。谢谢。

1个回答

10

这段代码将从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();
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接