首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

征服 Mongodb 之 《MongoDB权威指南》读书笔记(1)

2013-01-26 
征服 Mongodb 之 《MongoDB权威指南》读书笔记(一)?? ? 相关文章:? ??征服 Mongodb 之 安装与主从配置? ? 关

征服 Mongodb 之 《MongoDB权威指南》读书笔记(一)

?

? ? 相关文章:

? ??征服 Mongodb 之 安装与主从配置

? ? 关于如何安装、配置、启动MongoDB等,参考上篇文章。

?

? ? 一、常规命令登录

? ? 类似于MySQL登录,可参考如下命令:

?

# mongo --helpMongoDB shell version: 2.0.7usage: mongo [options] [db address] [file names (ending in .js)]db address can be:  foo                   foo database on local machine  192.169.0.5/foo       foo database on 192.168.0.5 machine  192.169.0.5:9999/foo  foo database on 192.168.0.5 machine on port 9999options:  --shell               run the shell after executing files  --nodb                don't connect to mongod on startup - no 'db address' arg expected  --norc                will not run the ".mongorc.js" file on start up  --quiet               be less chatty  --port arg            port to connect to  --host arg            server to connect to  --eval arg            evaluate javascript  -u [ --username ] arg username for authentication  -p [ --password ] arg password for authentication  -h [ --help ]         show this usage information  --version             show version information  --verbose             increase verbosity  --ipv6                enable IPv6 support (disabled by default)file names: a list of files to run. files have to end in .js and will exit after unless --shell is specified
?

?

? ? 譬如,我经常这么用,一步到位:

??

?

# mongo 10.11.20.140/zlexMongoDB shell version: 2.0.7connecting to: 10.11.20.140/zlex> 
?

?

?查看当前数据库/切换数据库? ??
# mongo MongoDB shell version: 2.0.7connecting to: test> dbtest> use zlexswitched to db zlex> 
?
?查看当前数据库下的表,及索引?
> show collectionssystem.indexestestuser
??? system.indexes索引信息

? ? test、user是数据表

?

?查看当前数据库、表状态
> db.stats(){        "db" : "test",        "collections" : 6,        "objects" : 16,        "avgObjSize" : 44.75,        "dataSize" : 716,        "storageSize" : 32768,        "numExtents" : 6,        "indexes" : 4,        "indexSize" : 32704,        "fileSize" : 201326592,        "nsSizeMB" : 16,        "ok" : 1}> db.blog.stats(){        "ns" : "test.blog",        "count" : 0,        "size" : 0,        "storageSize" : 8192,        "numExtents" : 1,        "nindexes" : 1,        "lastExtentSize" : 8192,        "paddingFactor" : 1.56,        "flags" : 1,        "totalIndexSize" : 8176,        "indexSizes" : {                "_id_" : 8176        },        "ok" : 1}
? ?PS:MongoDB 1.8支持16MB的消息长度
??一些边边角角的函数,你懂滴,横向思维下征服 Mongodb 之 《MongoDB权威指南》读书笔记(1)
> db.help()DB methods:        db.addUser(username, password[, readOnly=false])        db.auth(username, password)        db.cloneDatabase(fromhost)        db.commandHelp(name) returns the help for the command        db.copyDatabase(fromdb, todb, fromhost)        db.createCollection(name, { size : ..., capped : ..., max : ... } )        db.currentOp() displays the current operation in the db        db.dropDatabase()        db.eval(func, args) run code server-side        db.getCollection(cname) same as db['cname'] or db.cname        db.getCollectionNames()        db.getLastError() - just returns the err msg string        db.getLastErrorObj() - return full status object        db.getMongo() get the server connection object        db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair        db.getName()        db.getPrevError()        db.getProfilingLevel() - deprecated        db.getProfilingStatus() - returns if profiling is on and slow threshold         db.getReplicationInfo()        db.getSiblingDB(name) get the db at the same server as this one        db.isMaster() check replica primary status        db.killOp(opid) kills the current operation in the db        db.listCommands() lists all the db commands        db.logout()        db.printCollectionStats()        db.printReplicationInfo()        db.printSlaveReplicationInfo()        db.printShardingStatus()        db.removeUser(username)        db.repairDatabase()        db.resetError()        db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }        db.serverStatus()        db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all        db.shutdownServer()        db.stats()        db.version() current version of the server        db.getMongo().setSlaveOk() allow queries on a replication slave server        db.fsyncLock() flush data to disk and lock server for backups        db.fsyncUnock() unlocks server following a db.fsyncLock()> 

?

?

? ? 二、CRUDCreate——insert? ? ?数据插入通过insert函数,先建立一个局部变量(post),可以有字符串,数字,数组,日期,内嵌文档等等。数据类型后面再说,就这么几种,比较简单。征服 Mongodb 之 《MongoDB权威指南》读书笔记(1)> post = {"title":"My Blog Post",... "content":"Here's my blog post.",... "date":new Date()}{ "title" : "My Blog Post", "content" : "Here's my blog post.", "date" : ISODate("2013-01-23T05:29:08.151Z")}> db.blog.insert(post)> Read——find/findOne> db.blog.find(){ "_id" : ObjectId("50ff75376201fe04d53e42ed"), "title" : "My Blog Post", "content" : "Here's my blog post.", "date" : ISODate("2013-01-23T05:29:08.151Z") }? ? ?当前,我们只插入了一条记录,所以使用find函数只会取到一条记录。> db.blog.find({"title":"My Blog Post"}){ "_id" : ObjectId("50ff75376201fe04d53e42ed"), "title" : "My Blog Post", "content" : "Here's my blog post.", "date" : ISODate("2013-01-23T05:29:08.151Z") }? ? 如果条件符合,将会有多条数据。> db.stats(){ "db" : "test", "collections" : 6, "objects" : 16, "avgObjSize" : 44.75, "dataSize" : 716, "storageSize" : 32768, "numExtents" : 6, "indexes" : 4, "indexSize" : 32704, "fileSize" : 201326592, "nsSizeMB" : 16, "ok" : 1}> db.blog.stats(){ "ns" : "test.blog", "count" : 0, "size" : 0, "storageSize" : 8192, "numExtents" : 1, "nindexes" : 1, "lastExtentSize" : 8192, "paddingFactor" : 1.56, "flags" : 1, "totalIndexSize" : 8176, "indexSizes" : { "_id_" : 8176 }, "ok" : 1} ? ??_id是记录中的主键,默认是ObjectId类型,类似的还有_class,作为类路径名。
> post.comments=[][ ]> db.blog.update({"title":"My Blog Post"},post)? ? ?查询该数据结果:> db.blog.find(){ "_id" : ObjectId("50ff75376201fe04d53e42ed"), "title" : "My Blog Post", "content" : "Here's my blog post.", "date" : ISODate("2013-01-23T05:29:08.151Z"), "comments" : [ ] }> post.comments="desc"desc> db.blog.update({"title":"My Blog Post"},post)> db.blog.find(){ "_id" : ObjectId("50ff75376201fe04d53e42ed"), "title" : "My Blog Post", "content" : "Here's my blog post.", "date" : ISODate("2013-01-23T05:29:08.151Z"), "comments" : "desc" }? ? 只要数据类型支持,怎么写都可以。征服 Mongodb 之 《MongoDB权威指南》读书笔记(1)Delete——remove> db.blog.remove({"title" : "My Blog Post"})> db.blog.find({"title" : "My Blog Post"})> ? ? ?如果不加条件,就是全部删除。征服 Mongodb 之 《MongoDB权威指南》读书笔记(1){"x":null}
    undefined:未定义
    {"x":undefined}

    ?

      boolean:布尔,'true' | 'false'{"x":true}double:浮点数,不管是32位,还是64位的整数,最后都被统一为64位浮点数{"x":3.14}{"x":314}? ? ?在JavaScript中只有一种数字类型,在MongoDB中有3中数字类型(32位/64位整数、64位浮点数)。为了完全兼容这三种数字类型,在shell操作时,都统一为64位浮点数。
      {"x":"test"}?id:唯一标识{"x":new ObjectId()}
        ?Date:日期
        {"x":new Date()}
          ?Arrary:数组
          {"x":["a", "b", "c"]}
          {"x":{"name":"zlex"}}{"x": function(){/* ... */}}{"x": /foobar/i}

热点排行