gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:44:28 25 4
gpt4 key购买 nike

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

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

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

因此,为了避免这种情况,是否可以将所有导入或导出命令放入批处理或 JavaScript 文件中,并在单次执行中运行该文件?

如何解决这个问题?

最佳答案

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

关于javascript - 如何使用单个批处理文件或 javascript 导入或导出多个 mongo 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43660917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com