我使用的是Robomongo 0.8.4,我在单个数据库中有15个集合。每次使用CMD手动执行导出或导入时。例如,如果我需要10个导入集合,在CMD中运行10次mongo命令。我的示例import命令:
CD C:\Program Files\MongoDB\Server\3.2\bin>
mongoimport --db sampleDB --collection user1 --type json --file D:\user.json
因此,是否可以将所有导入或导出命令放入批处理或javascript文件中,并在单次执行中运行该文件?
如何解决这个问题?
发布于 2017-04-27 23:13:45
如果您安装了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 (/*....*/)
})
发布于 2017-04-27 23:01:21
所以只需要准备一个文本文件,用换行符分隔整个命令,并像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
)
但是展开list以获得您需要的所有导出内容。
发布于 2019-11-16 01:01:32
我正在寻找一个围绕网络的解决方案。我发现mongorestore可能是一个更简单的选择。也许我误解了你的问题的上下文,但我是这么做的。
mongorestore -d mongodb --dir=folderWithJsonCollections
https://stackoverflow.com/questions/43660917
复制相似问题