使用MongoDB Shell

来源:互联网 发布:网络安全法的特点 编辑:程序博客网 时间:2024/06/08 10:58

MongoDB Shell

1.shell连接mongodb

通常连接mongodb,这么做即可:

$ mongo some-host:30000/myDB

db现在就指向了some-host:30000上的myDB数据库。

启动mongo shell不连接到任何mongod有时很方便。通过–nodb参数启动shell,启动时就不会连接到任何数据库:

$ mongo --nodb

启动之后,在需要时运行new Mongo(hostname)命令就可以连接到想要的mongod了:

> conn = new Mongo("some-host:30000")connection to some-host:30000> db = conn.getDB("myDB")myDB

此时,就可以像平常一样使用db了。任何时候都可以使用这些命令来连接到不同的数据库或者服务器。

2.MongoDB shell内置了帮助文档,可以使用help命令查看:
> help        db.help()                    help on db methods        db.mycoll.help()             help on collection methods        sh.help()                    sharding helpers        rs.help()                    replica set helpers        help admin                   administrative help        help connect                 connecting to a db help        help keys                    key shortcuts        help misc                    misc things to know        help mr                      mapreduce        show dbs                     show database names        show collections             show collections in current database        show users                   show users in current database        show profile                 show most recent system.profile entries with time >= 1ms        show logs                    show the accessible logger names        show log [name]              prints out the last segment of log in memory, 'global' is default        use <db_name>                set current database        db.foo.find()                list objects in collection foo        db.foo.find( { a : 1 } )     list objects in foo where a == 1        it                           result of the last line evaluated; use to further iterate        DBQuery.shellBatchSize = x   set default number of items to display on shell        exit                         quit the mongo shell>

可以通过db.help()查看数据库级别的帮助,使用db.mycoll.help()查看集合级别的帮助。
如果想知道一个函数是做什么用的,可以直接在shell输入函数名(不带小括号),这样就可以看到相应的实现代码。

> db.blog.updatefunction ( query , obj , upsert , multi ){    var parsed = this._parseUpdate(query, obj, upsert, multi);    var query = parsed.query;    var obj = parsed.obj;    var upsert = parsed.upsert;    var multi = parsed.multi;    var wc = parsed.wc;    var result = undefined;    var startTime = (typeof(_verboseShell) === 'undefined' ||                     !_verboseShell) ? 0 : new Date().getTime();    if ( this.getMongo().writeMode() != "legacy" ) {        var bulk = this.initializeOrderedBulkOp();        var updateOp = bulk.find(query);        if (upsert) {            updateOp = updateOp.upsert();        }        if (multi) {            updateOp.update(obj);        }        else {            updateOp.updateOne(obj);        }        try {            result = bulk.execute(wc).toSingleResult();        }        catch( ex ) {            if ( ex instanceof BulkWriteError || ex instanceof WriteCommandError ) {                result = ex.toSingleResult();            }            else {                // Other exceptions thrown                throw Error(ex);            }        }    }    else {        this._validateUpdateDoc(obj);        this.getMongo().update(this._fullName, query, obj, upsert, multi);        // enforce write concern, if required        if (wc)            result = this.runCommand("getLastError", wc instanceof WriteConcern ? wc.toJSON() : wc);    }    this._printExtraInfo("Updated", startTime);    return result;}>
3.使用shell执行脚本

mongodb执行js脚本,直接在命令中执行就可以了,如下:

>mongo script1.js script2.js script3.jsMongoDB shell version: 3.0.4connecting to: testloading file: script1.jsI am script1.jsloading file: script2.jsI am script2.jsloading file: script3.jsI am script3.js>

mongo shell会依次执行传入的脚本,然后退出。
如果希望使用指定的主机/端口上的mongod运行脚本,需要先指定地址,然后再跟上脚本文件的名称:

$ mongo --quiet server-1:30000/foo script1.js script2.js script3.js

这样就将db指向server-1:30000上的foo数据库,然后执行三个脚本后退出。
其中:在脚本中使用print()函数输出信息,–quiet选项使shell不打印版本等信息。
也可以使用load()函数,从交互式shell中运行脚本:

> load("script1.js")I am script1.jstrue>

在脚本中可以访问db变量,以及其他全局变量。然而,shell辅助函数(比如”use db”和”show collections”)不可以在文件中使用。这些辅助函数都有对应的JavaScript函数:

辅助函数 等价函数 use foo db.getSisterDB(“fool”) show dbs db.getMongo().getDBs() show collections db.getCollectionNames()

通过这些脚本将变量注入到shell非常有用的。

创建.mongorc.js文件

如果某些脚本会被频繁加载,可以将它们添加到mongorc.js文件中。这个文件会在启动shell时自动运行。
为了实用,可以使用这个脚本创建一些自己需要的全局变量,或者是为太长的名字创建一个简短的别名,也可以重写内置的函数。.mongorc.js最见的用途之一是移除那些比较“危险”的shell辅助函数。可以在这里集中重写这些方法,比如为dropDatabase或者deleteIndexes等辅助函数添加no选项,或者取消它们的定义。

var no = function() {    print("Not on my watch.");};// 禁止删除数据库db.dropDatabase = DB.prototype.dropDatabase = no;// 禁止删除集合DBCollection.prototype.drop = no;// 禁止删除索引DBCollection.prototype.dropIndex = no;

改变数据库函数时,要确保同时对db变量和DB原型进行改变(如上例所示)。如果只改变了其中一个,那么db变量可能没有改变,或者这些改变在新使用的所有数据库(运行use anotherDB命令)中都不会生效。
现在,如果试图调用这些函数,就会得到一条错误提示。注意,这种方式并不能保护数据库免受恶意用户的攻击,只能预防自己的手误。
如果在启动shell时指定–norc参数,就可以禁止加载.mongorc.js。

0 0
原创粉丝点击