加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Mongodb-functions

(2013-03-07 17:35:59)
标签:

it

分类: mongo
Mongodb-functions
目录 [隐藏]
1 1, 关于 mongodb 中 help 说明
2 2, 关于 mongodb 中 funciton 说明
3 3, 如何定义 function
4 4, 存储 function
1, 关于 mongodb 中 help 说明

> help;

> db.help();

> db.collections.help();

> db.functions.help();


2, 关于 mongodb 中 funciton 说明

关于帮助的命令,如果输入 > help; 则出现下面的内容, 可以看到关于 help函数的具体定义
> help;
function (x) {
    if (x == "mr") {
        print("\nSee also http://www.mongodb.org/display/DOCS/MapReduce");
        print("\nfunction mapf() {");
        print("  // 'this' holds current document to inspect");
        print("  emit(key, value);");
        print("}");
        print("\nfunction reducef(key,value_array) {");
        print("  return reduced_value;");
        print("}");
        print("\ndb.mycollection.mapReduce(mapf, reducef[, options])");
        print("\noptions");
        print("{[query : ]");
        print(" [, sort : ]");
        print(" [, limit : ]");
        print(" [, out : ]");
        print(" [, keeptemp: ]");
        print(" [, finalize : ]");
        print(" [, scope : ]");
        print(" [, verbose : true]}\n");
        return;
    } else if (x == "connect") {
        print("\nNormally one specifies the server on the mongo shell command line.  Run mongo --help to see those options.");
        print("Additional connections may be opened:\n");
        print("    var x = new Mongo('host[:port]');");
        print("    var mydb = x.getDB('mydb');");
        print("  or");
        print("    var mydb = connect('host[:port]/mydb');");
        print("\nNote: the REPL prompt only auto-reports getLastError() for the shell command line connection.\n");
        return;
    } else if (x == "keys") {
        print("Tab completion and command history is available at the command prompt.\n");
        print("Some emacs keystrokes are available too:");
        print("  Ctrl-A start of line");
        print("  Ctrl-E end of line");
        print("  Ctrl-K del to end of line");
        print("\nMulti-line commands");
        print("You can enter a multi line javascript expression.  If parens, braces, etc. are not closed, you will see a new line ");
        print("beginning with '...' characters.  Type the rest of your expression.  Press Ctrl-C to abort the data entry if you");
        print("get stuck.\n");
    } else if (x == "misc") {
        print("\tb = new BinData(subtype,base64str)  create a BSON BinData value");
        print("\tb.subtype()                         the BinData subtype (0..255)");
        print("\tb.length()                          length of the BinData data in bytes");
        print("\tb.hex()                             the data as a hex encoded string");
        print("\tb.base64()                          the data as a base 64 encoded string");
        print("\tb.toString()");
        print();
        print("\tb = HexData(subtype,hexstr)         create a BSON BinData value from a hex string");
        print("\tb = UUID(hexstr)                    create a BSON BinData value of UUID subtype");
        print("\tb = MD5(hexstr)                     create a BSON BinData value of MD5 subtype");
        print();
        print("\to = new ObjectId()                  create a new ObjectId");
        print("\to.getTimestamp()                    return timestamp derived from first 32 bits of the OID");
        print("\to.isObjectId()");
        print("\to.toString()");
        print("\to.equals(otherid)");
        return;
    } else if (x == "admin") {
        print("\tls([path])                      list files");
        print("\tpwd()                           returns current directory");
        print("\tlistFiles([path])               returns file list");
        print("\thostname()                      returns name of this host");
        print("\tcat(fname)                      returns contents of text file as a string");
        print("\tremoveFile(f)                   delete a file or directory");
        print("\tload(jsfilename)                load and execute a .js file");
        print("\trun(program[, args...])         spawn a program and wait for its completion");
        print("\trunProgram(program[, args...])  same as run(), above");
        print("\tsleep(m)                        sleep m milliseconds");
        print("\tgetMemInfo()                    diagnostic");
        return;
    } else if (x == "test") {
        print("\tstartMongodEmpty(args)        DELETES DATA DIR and then starts mongod");
        print("\t                              returns a connection to the new server");
        print("\tstartMongodTest(port,dir,options)");
        print("\t                              DELETES DATA DIR");
        print("\t                              automatically picks port #s starting at 27000 and increasing");
        print("\t                              or you can specify the port as the first arg");
        print("\t                              dir is /data/db// if not specified as the 2nd arg");
        print("\t                              returns a connection to the new server");
        print("\tresetDbpath(dirpathstr)       deletes everything under the dir specified including subdirs");
        print("\tstopMongoProgram(port[, signal])");
        return;
    } else if (x == "") {
        print("\tdb.help()                    help on db methods");
        print("\tdb.mycoll.help()             help on collection methods");
        print("\trs.help()                    help on replica set methods");
        print("\thelp admin                   administrative help");
        print("\thelp connect                 connecting to a db help");
        print("\thelp keys                    key shortcuts");
        print("\thelp misc                    misc things to know");
        print("\thelp mr                      mapreduce");
        print();
        print("\tshow dbs                     show database names");
        print("\tshow collections             show collections in current database");
        print("\tshow users                   show users in current database");
        print("\tshow profile                 show most recent system.profile entries with time >= 1ms");
        print("\tshow logs                    show the accessible logger names");
        print("\tshow log [name]              prints out the last segment of log in memory, 'global' is default");
        print("\tuse                 set current database");
        print("\tdb.foo.find()                list objects in collection foo");
        print("\tdb.foo.find( { a : 1 } )     list objects in foo where a == 1");
        print("\tit                           result of the last line evaluated; use to further iterate");
        print("\tDBQuery.shellBatchSize = x   set default number of items to display on shell");
        print("\texit                         quit the mongo shell");
    } else {
        print("unknown help option");
    }
}

原因是 help 后面没有跟相应的参数,如果输入

> help ;
则会有正确的提示




3, 如何定义 function


定义:
function my_erase() {
    db.books.find().forEach(function (obj) {print(obj);});
}

调用:

> my_erase();


修改的话,目前没有看到如何修改,只能重新定义这个函数,覆盖原来的旧的函数。

> my_erase;
这个命令来显示这个函数的定义


4, 存储 function


Storing functions server-side
Note: we recommend not using server-side stored functions when possible. As these are code it is likely best to store them with the rest of your code in a version control system.
官方网站不推荐是存储方法到服务器端, 参考地址:
There is a special system collection called system.js that can store JavaScript functions to be reused. To store a function, you would do:

db.system.js.save( { _id : "foo" , value : function( x , y ){ return x + y; } } );
_id is the name of the function, and is unique per database.

Once you do that, you can use foo from any JavaScript context (db.eval, $where, map/reduce)

Here is an example from the shell:

>db.system.js.save({ "_id" : "echo", "value" : function(x){return x;} })
>db.eval_r("echo('test')")
test

See http://www.mongodb.org/display/DOCS/Server-side+Code+Execution http://github.com/mongodb/mongo/tree/master/jstests/storefunc.js for a full example.

0

阅读 收藏 喜欢 打印举报/Report
前一篇:Mongodb-管理
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有