`
marlonyao
  • 浏览: 249115 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

扩充mongodb shell

阅读更多
因为项目对mongodb数据库的结构做了一点修改,仅仅是是因为添加/删除一列就导致我使用python写了两个小程序来实现这一功能,而这样的功能在MySQL等关系数据库实际就是一条alter table命令的事。事后我就思考有没有简单的方法去实现这一点,一种方法就是用python实现类似MySQL修改数据模式的一套,这涉及到语法解析,并不简单。第二种方法就是扩展mongo shell,既然mongo shell可以运行javascript,就应当可以写javascript来扩充shell,通过mongo --help果然发现发现mongo可以直接运行javascript,并且通过加上--shell参数可以保持当javascript脚本执行完成之后并不退出shell。

要用javascript去扩展shell,首先就得知道shell使用的javascript类型,这并不困难,因为mongodb开源,这里有mongo shell的javascript代码,从这里我们可以知道DBCollection代表一个collection,如果我们增加添加/删除列的功能,只需要为DBCollection添加相应的方法就可以了。
DBCollection.prototype.addColumn = function(name, value) {
	var cond = {};
	cond[name] = { $exists: false };
	var field = {};
	field[name] = value;
	this.update(cond, { '$set': field }, false, true);
}

DBCollection.prototype.dropColumn = function(name) {
	var field = {};
	field[name] = 1;
	this.update({}, {'$unset': field }, false, true);
}


这样,在命令行下输入"mongo --shell mongo.js",然后就可以用db.account.addColumn("is_active", true)来为account collection添加is_active列了。我们也可以将新的方法加入到db.foo.help()中去,免得日后忘记:
_original_help = DBCollection.prototype.help;
DBCollection.prototype.help = function() {
	_original_help.apply(this);
	var shortName = this.getName();
	print("\tdb." + shortName + ".addColumn(name[, value]) - add column if it doesn't exist");
	print("\tdb." + shortName + ".dropColumn(name) - remove column");
}


最后每次都要输入"mongo --shell mongo.js"也是很繁琐的事,所以将它作为mongo的alias添加到.bashrc(或者.bash_aliases,如果你也像我一样喜欢将所有alias放在一个单独的文件中)中去就显得很有必要了。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics