如何使用单个批处理文件或javascript导入或导出多个mongo集合

如何使用单个批处理文件或javascript导入或导出多个mongo集合,javascript,mongodb,batch-file,mongodb-query,robo3t,Javascript,Mongodb,Batch File,Mongodb Query,Robo3t,我使用的是Robomongo 0.8.4,在单个数据库中有15个集合。每次使用CMD手动执行导出或导入。例如,如果我需要获取10个导入集合,那么可以在CMD中运行10次mongo命令。 我的示例导入命令: CD C:\Program Files\MongoDB\Server\3.2\bin> mongoimport--db sampleDB--collection user1--type json--file D:\user.json 所以,避免这种情况,是否可以将所有导入或导出命令放在

我使用的是Robomongo 0.8.4,在单个数据库中有15个集合。每次使用CMD手动执行导出或导入。例如,如果我需要获取10个导入集合,那么可以在CMD中运行10次mongo命令。 我的示例导入命令:

CD C:\Program Files\MongoDB\Server\3.2\bin>
mongoimport--db sampleDB--collection user1--type json--file D:\user.json

所以,避免这种情况,是否可以将所有导入或导出命令放在批处理或javascript文件中,并在单个执行中运行该文件


如何解决这个问题?

所以只需准备一个文本文件,其中包含以换行符分隔的整个命令,并将其像myscript.bat一样保存,然后运行它

CD "C:\Program Files\MongoDB\Server\3.2\bin>"
set list=user1 user2 user3
for %%a in (%list%) do (
   mongoimport --db sampleDB --collection %%a --type json --file D:\%%a.json
)
但扩展列表以获得所需的导出


如果安装了NodeJ,可以尝试以下脚本:

// This script list all the collections from the database
// and execute a mongoimport command corresponding to the collection name

// npm install --save shelljs
// npm install --save mongojs

var shell = require('shelljs')
var mongojs = require('mongojs')
var db = mongojs('username:password@localhost:27017/sampleDB')
db.getCollectionNames(function (err, names) {
  if (err) {
    console.log(err)
    process.exit(1)
  }
  names.forEach((name) => {
    var cmd = 'mongoimport --db sampleDB --collection ' + name + ' --type json --file D:\\' + name + '.json'
    console.log('executing: ' + cmd)
    shell.exec(cmd, function (code, stdout, stderr) {
      if (code != 0) {
        console.error('Error: ' + code)
        console.log('Program output:', stdout)
        console.log('Program stderr:', stderr)
      }
    })
  })
  process.exit(0)
})
注1

您需要安装shelljs和mongjs npm软件包

注2

此脚本假定数据库中已经存在一些集合, 并且在D中有一个以每个集合命名的文件:\

注3: 我还没有测试shell.exec部分

注4

如果不想直接从数据库读取集合名称,可以直接在脚本中硬编码集合名称:

var collections = [{coll: "user1", file: "user"}, {coll: "admin", file: "user2"}]
collections.forEach((item) => {
  var cmd = 'mongoimport --db sampleDB --collection ' + item.coll + ' --type json --file D:\\' + item.file + '.json'
  shell.exec (/*....*/)
})

我在网上寻找解决方案。我发现mongorestore可能是一个更容易的选择。也许我误解了你问题的来龙去脉,但以下是我所做的

mongorestore -d mongodb --dir=folderWithJsonCollections

您可以尝试编写自己的nodejs脚本,该脚本将在数据库中的每个集合上循环,并使用shelljs执行导出命令您可以将代码添加到您的答案中,而不是链接到代码的图像吗?