MongoDb-将数据库导出到js脚本(类似于rockmongo导出) [英] MongoDb - Export database to js script (similar to rockmongo export)

查看:59
本文介绍了MongoDb-将数据库导出到js脚本(类似于rockmongo导出)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从命令行是否可以将MongoDb数据库转储到可以由mongo shell解释的javascript文件中?我正在寻找一种完全可以执行RockMongo Export函数功能的方法,但是我需要能够从命令行脚本中调用它.我到处都在寻找可以做到这一点的东西,但是我似乎只能找到mongoexport和mongodump,它们似乎并没有执行我想要的操作,因为它们只是创建JSON文件.

之所以需要这样做,是因为Codeception的MongoDb模块需要这种格式的文件才能在每次测试后恢复数据库.我想编写一个脚本来自动执行此过程,这样我就不必不断浏览RockMongo并生成转储.

提前谢谢!

解决方案

万一其他人碰巧发现了这个问题,我终于找到了适用于我的方案的解决方案.我不得不接受Markus的建议并提出自己的解决方案,但是我发现了一个名为bsondump的mongodb命令,该命令使事情变得简单得多.

因此,在我的脚本中,我首先使用mongodump创建我的收藏夹的BSON文件

  mongodump --db mydb --collection mycollection --out->mycollection.bson 

然后我使用bsondump将其转换为可以在

我猜测可能有更好的方法来执行此操作,但是到目前为止,这似乎对我来说效果很好.感谢您为我指引正确的方向Markus!

Is there a way from the command line that I can dump a MongoDb database to a javascript file that can be interpreted by the mongo shell? I am looking for a way to do exactly what the RockMongo Export function does, but I need to be able to call it from a command line script. I've looked everywhere for something that does this but all I can seem to find is mongoexport and mongodump which don't seem to do what I want, as these just create JSON files.

The reason I need to do this is because codeception's MongoDb module requires a file in this format to restore the database after each test. I want to write a script to automate this process so that I don't have to constantly go through RockMongo and generate the dump.

Thanks in advance!

解决方案

In case anyone else happens to find this, I finally found a solution that works for my scenario. I had to take Markus' suggestion and kind of roll my own solution, but I discovered a mongodb command called bsondump that made things much easier.

So in my script I first use mongodump to create a BSON file of my collection

mongodump --db mydb --collection mycollection --out - > mycollection.bson

I then use bsondump to convert that into JSON that can be used in Shell Mode

bsondump mycollection.bson > mycollection.json

Finally, I'm using PHP so in my PHP script I loop through that json file and wrap each line in an insert statement.

$lines = file('mycollection.json');
$inserts = [];

foreach($lines as $line)
{
    $inserts[] = 'db.getCollection("mycollection").insert(' . trim($line) . ');' . PHP_EOL;
}

file_put_contents('output.js', $inserts);

I'm guessing there is probably a better way to do this, but so far this seems to be working nicely for me. Thanks for steering me in the right direction Markus!

这篇关于MongoDb-将数据库导出到js脚本(类似于rockmongo导出)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆