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

  1. [falcon@www.fwphp.cn  ~/mongodb]$ bin/mongo
  2. MongoDB shell version: 1.2.4-
  3. url: test
  4. connecting to: test
  5. type "help" for help
  6. > help
  7. HELP
  8.         Show  dbs                     显示数据库名
  9.         show  collections             显示当前数据库中的集合集
  10.         show  users                   显示当前数据库的用户
  11.         show  profile                显示最后系统用时大于1ms的系统概要
  12.         use <db name>                切换到数据库
  13.         db.help()                    help on DB methods
  14.         db.foo.help()                help on collection methods
  15.         db.foo.find()                list objects in collection foo
  16.         db.foo.find( { a : 1 } )     list objects in foo where a == 1
  17.         it                           result of the last line evaluated; use to further iterate
  18. > show dbs   默认情况下有2数据库
  19. admin
  20. local
  21. > use admin                切换到admin数据库
  22. switched to db admin
  23. > show collections                显示admin数据库下面的集合集
  24. system.indexes

下面我们来简单的新建集合集,插入、更新、查询数据, 体验mongodb带给我们不一样的生活
新建数据库的方法是在
新建集合集:

  1. > db.createCollection("user");
  2. { "ok" : 1 }
  3. > show collections
  4. system.indexes
  5. user
  6. >

插入数据:

  1. > db.user.insert({uid:1,username:"Falcon.C",age:25});
  2. > db.user.insert({uid:2,username:"aabc",age:24});  

查询数据:

  1. > db.user.find();
  2. { "_id" : ObjectId("4b81e74c1f0fd3b9545cba43"), "uid" : 1, "username" : "Falcon.C", "age" : 25 }
  3. { "_id" : ObjectId("4b81e74d1f0fd3b9545cba44"), "uid" : 2, "username" : "aabc", "age" : 24 }

查询数据的方式很丰富,有类似于SQL的条件查询,将 会在以后的文档中详细介绍
如:我想查询uid为1的用户信息

  1. > db.user.find({uid:1});
  2. { "_id" : ObjectId("4b81e74c1f0fd3b9545cba43"), "uid" : 1, "username" : "Falcon.C", "age" : 25 }

等等,丰富的查询还有limit ,sort ,findOne,distinct等


更新数据:

  1. > db.user.update({uid:1},{$set:{age:26}})
  2. > db.user.find();                        
  3. { "_id" : ObjectId("4b81e76f1f0fd3b9545cba45"), "uid" : 1, "username" : "Falcon.C", "age" : 26 }
  4. { "_id" : ObjectId("4b81e7701f0fd3b9545cba46"), "uid" : 2, "username" : "aabc", "age" : 24 }
  5. > db.user.update({uid:1},{$inc:{age:-1}})
  6. > db.user.find();                        
  7. { "_id" : ObjectId("4b81e76f1f0fd3b9545cba45"), "uid" : 1, "username" : "Falcon.C", "age" : 25 }
  8. { "_id" : ObjectId("4b81e7701f0fd3b9545cba46"), "uid" : 2, "username" : "aabc", "age" : 24 }
  9. >

出 了以上的2种用法,更新的条件还有$unset、$push 、$pushAll 、$pop 、$pull 、$pullAll


以上就是MongoDB简单的使用介绍,在以后的文档中将会详细的介绍mongoDB非常酷的CURD方法,mongoDB的Replication及分 布式

MongoDB的使用技巧

如果想查看当前连接在哪个数据 库下面,可以直接输入db

  1. > db
  2. Admin

想切换到test数据库

  1. > use test
  2. switched to db test
  3. > db
  4. Test

想 查看test下有哪些表或者叫collection,可以输入

  1. > show collections
  2. system.indexes
  3. user

想 知道mongodb支持哪些命令 ,可以直接输入help

  1. > help
  2. HELP
  3.         show dbs                     show database names
  4.         show collections             show collections in current database
  5.         show users                   show users in current database
  6.         show profile                 show most recent system.profile entries with time >= 1ms
  7.         use <db name>                set curent database to <db name>
  8.         db.help()                    help on DB methods
  9.         db.foo.help()                help on collection methods
  10.         db.foo.find()                list objects in collection foo
  11.         db.foo.find( { a : 1 } )     list objects in foo where a == 1
  12.         it                           result of the last line evaluated; use to further iterate

如果想知道当前数据库支持哪些方法:

  1. > db.help();
  2. DB methods:
  3.         db.addUser(username, password) 添加数据库授权用户
  4.         db.auth(username, password)                访问 认证
  5.         db.cloneDatabase(fromhost) 克隆数据库
  6.         db.commandHelp(name) returns the help for the command
  7.         db.copyDatabase(fromdb, todb, fromhost)  复制数据库
  8.         db.createCollection(name, { size : ..., capped : ..., max : ... } ) 创建表
  9.         db.currentOp() displays the current operation in the db
  10.         db.dropDatabase()        删除当前数据库
  11.         db.eval(func, args) run code server-side
  12.         db.getCollection(cname) same as db['cname'] or db.cname
  13.         db.getCollectionNames()        获取当前数据库的表名
  14.         db.getLastError() - just returns the err msg string
  15.         db.getLastErrorObj() - return full status object
  16.         db.getMongo() get the server connection object
  17.         db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
  18.         db.getName()
  19.         db.getPrevError()
  20.         db.getProfilingLevel()
  21.         db.getReplicationInfo()
  22.         db.getSisterDB(name) get the db at the same server as this onew
  23.         db.killOp() kills the current operation in the db
  24.         db.printCollectionStats()   打印各表的状态信息
  25.         db.printReplicationInfo()        打印主数据库的复制状态信息
  26.         db.printSlaveReplicationInfo()        打印从数据库的复制状态信息
  27.         db.printShardingStatus()                打印分片状态信息
  28.         db.removeUser(username) 删除数据库用户
  29.         db.repairDatabase() 修复数据库
  30.         db.resetError()
  31.         db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }
  32.         db.setProfilingLevel(level) 0=off 1=slow 2=all
  33.         db.shutdownServer ()
  34.         db.version() current version of the server

如果想知道当前数据库下的表或者表 collection支持哪些方法,可以使用一下命令如:

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

Mongodb的备份工具 mongodump

如果想备份数据库test 如:

  1. [falcon@www.fwphp .cn  ~/mongodb/bin]$ ./mongodump --help
  2. options:
  3.   --help                   produce help message
  4.   -h [ --host ] arg        mongo host to connect to
  5.   -d [ --db ] arg          database to use
  6.   -c [ --collection ] arg  collection to use (some commands)
  7.   -u [ --username ] arg    username
  8.   -p [ --password ] arg    password
  9.   --dbpath arg             directly access mongod data files in this path,
  10.                            instead of connecting to a mongod instance
  11.   -v [ --verbose ]         be more verbose (include multiple times for more
  12.                            verbosity e.g. -vvvvv)
  13.   -o [ --out ] arg (=dump) output directory
  14. [falcon@www.fwphp.cn  ~/mongodb/bin]$ [color=Blue]./mongodump -d test -o test/[/color]
  15. connected to: 127.0.0.1
  16. DATABASE: test         to         test/test
  17.         test.user to test/test/user.bson
  18.                  100000 objects
  19.         test.system.indexes to test/test/system.indexes.bson
  20.                  1 objects
  21. [falcon@www.fwphp.cn  ~/mongodb/bin]$ ls
  22. 2     mongo   mongodump    mongofiles   mongorestore  mongosniff
  23. dump  mongod  mongoexport  mongoimport  mongos     test

MongoDB的数据恢复工具 mongorestore

查看test库中的表

  1. > show collections
  2. system.indexes
  3. User

删除user表

  1. > db.user.drop();
  2. True

  3. > show collections
  4. System.indexes

现在利用mongorestore表恢复刚才利用 mongodump备份的数据

  1. [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore --help
  2. usage: ./mongorestore [options] [directory or filename to restore from]
  3. options:
  4.   --help                  produce help message
  5.   -h [ --host ] arg       mongo host to connect to
  6.   -d [ --db ] arg         database to use
  7.   -c [ --collection ] arg collection to use (some commands)
  8.   -u [ --username ] arg   username
  9.   -p [ --password ] arg   password
  10.   --dbpath arg            directly access mongod data files in this path,
  11.                           instead of connecting to a mongod instance
  12.   -v [ --verbose ]        be more verbose (include multiple times for more
  13.                           verbosity e.g. -vvvvv)

  14. [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore -d test -c user test/test/user.bson
  15. connected to: 127.0.0.1
  16. test/test/user.bson
  17.          going into namespace [test.user]

  18.          100000 objects

User表中的10w条记录已经恢复

  1. > show collections
  2. system.indexes
  3. user
  4. > db.user.find();
  5. { "_id" : ObjectId("4b9c8db08ead0e3347000000"), "uid" : 1, "username" : "Falcon.C-1" }
  6. { "_id" : ObjectId("4b9c8db08ead0e3347010000"), "uid" : 2, "username" : "Falcon.C-2" }
  7. { "_id" : ObjectId("4b9c8db08ead0e3347020000"), "uid" : 3, "username" : "Falcon.C-3" }
  8. { "_id" : ObjectId("4b9c8db08ead0e3347030000"), "uid" : 4, "username" : "Falcon.C-4" }
  9. { "_id" : ObjectId("4b9c8db08ead0e3347040000"), "uid" : 5, "username" : "Falcon.C-5" }
  10. .................
  11. has more

mongodb还提供了HTTP查看 运行 状态及restfull的接口
默认的访问 端口 是28017



原文链接: http://blog.csdn.net/wangkuifeng0118/article/details/7335610

转载于:https://my.oschina.net/chen106106/blog/49020

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值