纸水仙 发表于 2015-11-11 10:17:14

MongoDB数据库文档大全

  MongoDB数据库简单介绍
MongoDB是一个高性能 ,开源 ,无模式的文档型数据库,它在许多场景下可用于替代传统的关系型数据库或键/值存储模式。MongoDB是用C++开发, 提供了以下功能:
  

[*]面向集合的存储:适合存储对象及JSON形式的数据。
[*]动态查询:Mongo支持丰富的查询表达式。查询指令使用JSON形式的 标记,可轻易查询文档中内嵌的对象及数组。
[*]完整的索引支持:包括文档内嵌对象及数组。Mongo的查询优化 器会分析查询表达式,并生成一个高效的查询计划。
[*]查 询监视:Mongo包含一个监视工具 用于分析数据库操作的性能。
[*]复制 及自动故障转移:Mongo数据库支持服务器 之间的数据复制,支持主-从模式及服务 器之间的相互复制。复制的主要目标是提供冗余及自 动故障转移。
[*]高效的传统存储方式:支持二进制数据及大型对象(如照片或图片)。
[*]自动分片以支持云级别的伸缩性(处于 早期alpha阶段):自动分片功能支持水平的数据库集群 ,可动态添加额外的机器。
  
MongoDB的主要目标是在键/值存储方式(提供了高性能和高度伸缩性)以及传统的RDBMS系统 (丰富的功能)架起一座桥梁,集两者的优势于一 身。根据官方网站的描述,Mongo 适合用于以下场景:
  

[*]网站数据:Mongo非常适合实时的插入,更新与查询,并具备网站实时数据存储所需的复制及高度伸缩性。
[*]缓存 :由于性能很高,Mongo也适合作为信息基础设施的缓存层。在系统重启之后,由Mongo搭建的持久化缓存层可以避免下层的数据源 过载。
[*]大尺寸,低价值的数据:使用传统的关系型数据库存储一些数据时可能会比较昂贵,在此之前,很 多时候程序员往往会选择传统的文件 进行存储。
[*]高伸缩性的场景:Mongo非常适合由数十或数百台服务器组成的数据库。Mongo的路线图中已经包含对MapReduce引擎的内置支 持。
[*]用于 对象及JSON数据的存储:Mongo的BSON数据格式非常适合文档化格式的存储 及查询。
  
自然,MongoDB的使用也会有一些限制,例如它不适合:
  

[*]高度事务性的系统:例如银行或会计系统。传统的关系型数据库目前还是更适用于需要大量原子性复杂事务的应用 程序。
[*]传统的商业智能应用:针对特定问题的BI数据库会对产生高度优化的查询方式。对于此类应用,数据仓库可能是更合适的选择。
[*]需要SQL的问题

  MongoDB支持OS X、Linux及Windows等操作系统 ,并提供了Python,PHP,Ruby,Java,C,C#,Javascript,Perl及C++语言的驱动程序,社区中也提供了对Erlang 及.NET等平台的驱动程序
  使用方法:
  利用客户端程序mongo登录mongoDB

[*]$ bin/mongo
[*]MongoDB shell version: 1.2.4-
[*]url: test
[*]connecting to: test
[*]type "help" for help
[*]> help
[*]HELP
[*]      Showdbs                     显示数据库名
[*]      showcollections             显示当前数据库中的集合集
[*]      showusers                   显示当前数据库的用户
[*]      showprofile                显示最后系统用时大于1ms的系统概要
[*]      use <db name>                切换到数据库
[*]      db.help()                  help on DB methods
[*]      db.foo.help()                help on collection methods
[*]      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
[*]> show dbs   默认情况下有2数据库
[*]admin
[*]local
[*]> use admin                切换到admin数据库
[*]switched to db admin
[*]> show collections                显示admin数据库下面的集合集
[*]system.indexes
  
  下面我们来简单的新建集合集,插入、更新、查询数据, 体验mongodb带给我们不一样的生活
新建数据库的方法是在
新建集合集:

[*]> db.createCollection(&quot;user&quot;);
[*]{ &quot;ok&quot; : 1 }
[*]> show collections
[*]system.indexes
[*]user
[*]>
  插入数据:

[*]> db.user.insert({uid:1,username:&quot;Falcon.C&quot;,age:25});
[*]> db.user.insert({uid:2,username:&quot;aabc&quot;,age:24});
  查询数据:

[*]> db.user.find();
[*]{ &quot;_id&quot; : ObjectId(&quot;4b81e74c1f0fd3b9545cba43&quot;), &quot;uid&quot; : 1, &quot;username&quot; : &quot;Falcon.C&quot;, &quot;age&quot; : 25 }
[*]{ &quot;_id&quot; : ObjectId(&quot;4b81e74d1f0fd3b9545cba44&quot;), &quot;uid&quot; : 2, &quot;username&quot; : &quot;aabc&quot;, &quot;age&quot; : 24 }
  查询数据的方式很丰富,有类似于SQL的条件查询,将 会在以后的文档中详细介绍
如:我想查询uid为1的用户信息

[*]> db.user.find({uid:1});
[*]{ &quot;_id&quot; : ObjectId(&quot;4b81e74c1f0fd3b9545cba43&quot;), &quot;uid&quot; : 1, &quot;username&quot; : &quot;Falcon.C&quot;, &quot;age&quot; : 25 }
  等等,丰富的查询还有limit ,sort ,findOne,distinct等


更新数据:

[*]> db.user.update({uid:1},{$set:{age:26}})
[*]> db.user.find();
[*]{ &quot;_id&quot; : ObjectId(&quot;4b81e76f1f0fd3b9545cba45&quot;), &quot;uid&quot; : 1, &quot;username&quot; : &quot;Falcon.C&quot;, &quot;age&quot; : 26 }
[*]{ &quot;_id&quot; : ObjectId(&quot;4b81e7701f0fd3b9545cba46&quot;), &quot;uid&quot; : 2, &quot;username&quot; : &quot;aabc&quot;, &quot;age&quot; : 24 }
[*]> db.user.update({uid:1},{$inc:{age:-1}})
[*]> db.user.find();
[*]{ &quot;_id&quot; : ObjectId(&quot;4b81e76f1f0fd3b9545cba45&quot;), &quot;uid&quot; : 1, &quot;username&quot; : &quot;Falcon.C&quot;, &quot;age&quot; : 25 }
[*]{ &quot;_id&quot; : ObjectId(&quot;4b81e7701f0fd3b9545cba46&quot;), &quot;uid&quot; : 2, &quot;username&quot; : &quot;aabc&quot;, &quot;age&quot; : 24 }
[*]>
出 了以上的2种用法,更新的条件还有$unset、$push 、$pushAll 、$pop 、$pull 、$pullAll


以上就是MongoDB简单的使用介绍,在以后的文档中将会详细的介绍mongoDB非常酷的CURD方法,mongoDB的Replication及分 布式  
MongoDB的使用技巧
  
  如果想查看当前连接在哪个数据 库下面,可以直接输入db

[*]> db
[*]Admin
  想切换到test数据库

[*]> use test
[*]switched to db test
[*]> db
[*]Test
  想 查看test下有哪些表或者叫collection,可以输入

[*]> show collections
[*]system.indexes
[*]user
  想 知道mongodb支持哪些命令 ,可以直接输入help

[*]> help
[*]HELP
[*]      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
[*]      use <db name>                set curent database to <db name>
[*]      db.help()                  help on DB methods
[*]      db.foo.help()                help on collection methods
[*]      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
  如果想知道当前数据库支持哪些方法:

[*]> db.help();
[*]DB methods:
[*]      db.addUser(username, password) 添加数据库授权用户
[*]      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()
[*]      db.getReplicationInfo()
[*]      db.getSisterDB(name) get the db at the same server as this onew
[*]      db.killOp() kills the current operation in the db
[*]      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.setProfilingLevel(level) 0=off 1=slow 2=all
[*]      db.shutdownServer ()
[*]      db.version() current version of the server
  如果想知道当前数据库下的表或者表 collection支持哪些方法,可以使用一下命令如:

[*]> db.user.help();user为表名
[*]DBCollection help
[*]      db.foo.count()                统计表的行数
[*]      db.foo.dataSize()      统计表数据的大小
[*]      db.foo.distinct( key ) - eg. db.foo.distinct( 'x' )                按照给定的条件除重
[*]      db.foo.drop() drop the collection 删除表
[*]      db.foo.dropIndex(name)删除指定索引
[*]      db.foo.dropIndexes() 删除所有索引
[*]      db.foo.ensureIndex(keypattern,options) - options should be an object with these possible fields: name, unique, dropDups增加索引
[*]      db.foo.find( , ) - first parameter is an optional query filter. second parameter is optional set of fields to return. 根据条件查找数据
[*]                                           e.g. db.foo.find( { x : 77 } , { name : 1 , x : 1 } )
[*]      db.foo.find(...).count()
[*]      db.foo.find(...).limit(n) 根据条件查找数据并返回指定记录数
[*]      db.foo.find(...).skip(n)
[*]      db.foo.find(...).sort(...) 查找排序
[*]      db.foo.findOne() 根据条件查询只查询一条数据
[*]      db.foo.getDB() get DB object associated with collection返回表所属的库
[*]      db.foo.getIndexes() 显示表的所有索引
[*]      db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) 根据条件分组
[*]      db.foo.mapReduce( mapFunction , reduceFunction , <optional params> )
[*]      db.foo.remove(query) 根据条件删除数据
[*]      db.foo.renameCollection( newName ) renames the collection重命名表
[*]      db.foo.save(obj) 保存数据
[*]      db.foo.stats()查看表的状态
[*]      db.foo.storageSize() - includes free space allocated to this collection 查询分配到表空间大小
[*]      db.foo.totalIndexSize() - size in bytes of all the indexes 查询所有索引的大小
[*]      db.foo.totalSize() - storage allocated for all data and indexes 查询表的总大小
[*]      db.foo.update(query, object[, upsert_bool]) 根据条件更新数据
[*]      db.foo.validate() - SLOW 验证表的详细信息
[*]      db.foo.getShardVersion() - only for use with sharding
  Mongodb的备份工具 mongodump

如果想备份数据库test 如:

[*]$ ./mongodump --help
[*]options:
[*]--help                   produce help message
[*]-h [ --host ] arg      mongo host to connect to
[*]-d [ --db ] arg          database to use
[*]-c [ --collection ] argcollection to use (some commands)
[*]-u [ --username ] arg    username
[*]-p [ --password ] arg    password
[*]--dbpath arg             directly access mongod data files in this path,
[*]                           instead of connecting to a mongod instance
[*]-v [ --verbose ]         be more verbose (include multiple times for more
[*]                           verbosity e.g. -vvvvv)
[*]-o [ --out ] arg (=dump) output directory
[*]$ ./mongodump -d test -o test/
[*]connected to: 127.0.0.1
[*]DATABASE: test         to         test/test
[*]      test.user to test/test/user.bson
[*]               100000 objects
[*]      test.system.indexes to test/test/system.indexes.bson
[*]               1 objects
[*]$ ls
[*]2   mongo   mongodump    mongofiles   mongorestoremongosniff
[*]dumpmongodmongoexportmongoimportmongos   test
  MongoDB的数据恢复工具 mongorestore

查看test库中的表

[*]> show collections
[*]system.indexes
[*]User
  删除user表

[*]> db.user.drop();
[*]True
[*]
[*]> show collections
[*]System.indexes
  现在利用mongorestore表恢复刚才利用 mongodump备份的数据

[*]$ ./mongorestore --help
[*]usage: ./mongorestore
[*]options:
[*]--help                  produce help message
[*]-h [ --host ] arg       mongo host to connect to
[*]-d [ --db ] arg         database to use
[*]-c [ --collection ] arg collection to use (some commands)
[*]-u [ --username ] arg   username
[*]-p [ --password ] arg   password
[*]--dbpath arg            directly access mongod data files in this path,
[*]                        instead of connecting to a mongod instance
[*]-v [ --verbose ]      be more verbose (include multiple times for more
[*]                        verbosity e.g. -vvvvv)
[*]
[*]$ ./mongorestore -d test -c user test/test/user.bson
[*]connected to: 127.0.0.1
[*]test/test/user.bson
[*]         going into namespace
[*]
[*]         100000 objects
  User表中的10w条记录已经恢复

[*]> show collections
[*]system.indexes
[*]user
[*]> db.user.find();
[*]{ &quot;_id&quot; : ObjectId(&quot;4b9c8db08ead0e3347000000&quot;), &quot;uid&quot; : 1, &quot;username&quot; : &quot;Falcon.C-1&quot; }
[*]{ &quot;_id&quot; : ObjectId(&quot;4b9c8db08ead0e3347010000&quot;), &quot;uid&quot; : 2, &quot;username&quot; : &quot;Falcon.C-2&quot; }
[*]{ &quot;_id&quot; : ObjectId(&quot;4b9c8db08ead0e3347020000&quot;), &quot;uid&quot; : 3, &quot;username&quot; : &quot;Falcon.C-3&quot; }
[*]{ &quot;_id&quot; : ObjectId(&quot;4b9c8db08ead0e3347030000&quot;), &quot;uid&quot; : 4, &quot;username&quot; : &quot;Falcon.C-4&quot; }
[*]{ &quot;_id&quot; : ObjectId(&quot;4b9c8db08ead0e3347040000&quot;), &quot;uid&quot; : 5, &quot;username&quot; : &quot;Falcon.C-5&quot; }
[*].................
[*]has more
mongodb还提供了HTTP查看运行 状态及restfull的接口
默认的访问端口 是28017


         版权声明:本文为博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: MongoDB数据库文档大全