如果你安装了 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 (/*....*/)
})