【问题标题】:How to import or export multiple mongo collection using single batch file or javascript如何使用单个批处理文件或 javascript 导入或导出多个 mongo 集合
【发布时间】:2017-09-25 10:24:45
【问题描述】:

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

CD C:\Program Files\MongoDB\Server\3.2\bin>

mongoimport --db sampleDB --collection user1 --type json --file D:\user.json

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

如何解决这个问题?

【问题讨论】:

  • 您可以尝试编写自己的 nodejs 脚本,该脚本将遍历数据库中的每个集合并使用 ShellJs 执行导出命令

标签: javascript mongodb batch-file mongodb-query robo3t


【解决方案1】:

如果你安装了 NodeJs,你可以试试这样的脚本:

// 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 (/*....*/)
})

【讨论】:

    【解决方案2】:

    所以只需准备文本文件,其中包含由换行符分隔的整个命令,并将其保存为 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
    )
    

    但可以根据需要扩展列表。

    How do you loop in a Windows batch file?

    Image with sample batch file

    【讨论】:

    • 您能否将代码添加到您的答案中,而不是链接到代码的图像?
    【解决方案3】:

    我正在网上寻找解决方案。我发现 mongorestore 可能是一个更简单的选择。也许我误解了你的问题的上下文,但这就是我所做的。

    mongorestore -d mongodb --dir=folderWithJsonCollections
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      相关资源
      最近更新 更多