开发者

MongoDB Administration through command line scripts

in mysql I can administer my database (the primary goal is to a have an automate开发者_开发百科d build of the database by sequentially applying changes to it with scripts) by running commands like this:

mysql -u root my_database < script_1.sql
mysql -u root my_database < script_2.sql

Where script_1.sql looks like this:

DROP DATABASE IF EXISTS my_database;
CRATE DATABASE my_database;

And script_2.sql something like this:

INSERT INTO ...

Ok, I want to to the same for mongo, but instead of running SQL commands I would like to run mongo db commands.

Is something like that possible?


First, in mongo, objects are created on the fly (when you insert the first object in the first collection of a database), so maybe you don't need to create database and collection.

Then you can use 2 different tools to populate your databases with objects : mongoimport and mongo

mongo -d myDatabase --eval  "db.aCollection.insert({_id : ..,....,....})"

or

mongo -d myDatabase --eval bob.js

can execute any javascript you want. This is done with a lock on the db, so do not use this on an instance that is used for requests.

The second method is to use mongoimport as said on other response. This is easier if you have a list of objects and no other type of commands. Note that objects are upserted (not inserted) so duplicates should not fail.


I guess import tool and batch files good fit for your needs.

For example, if you imported a file that looks like this:

{ "_id" : { "$oid" : "4e5bb37258200ed9aabc5d65" }, "name" : "Bob", "age" : 28, "address" : "123 fake street" }

by running

mongoimport -d test -c foo importfile.json

To drop database you can stop mongodb (also via batch file), remove database files,and start database again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜