设为首页 收藏本站
查看: 1355|回复: 0

[经验分享] MongoDB数据库文档大全

[复制链接]

尚未签到

发表于 2015-11-11 10:17:14 | 显示全部楼层 |阅读模式
  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

  • [falcon@www.fwphp.cn  ~/mongodb]$ bin/mongo
  • MongoDB shell version: 1.2.4-
  • url: test
  • connecting to: test
  • type "help" for help
  • > help
  • HELP
  •         Show  dbs                     显示数据库名
  •         show  collections             显示当前数据库中的集合集
  •         show  users                   显示当前数据库的用户
  •         show  profile                显示最后系统用时大于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 }
  查询数据的方式很丰富,有类&#20284;于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( [query] , [fields]) - 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([query]) 根据条件查询只查询一条数据
  •         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 如:

  • [falcon@www.fwphp .cn  ~/mongodb/bin]$ ./mongodump --help
  • 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)
  •   -o [ --out ] arg (=dump) output directory
  • [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./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
  • [falcon@www.fwphp.cn  ~/mongodb/bin]$ ls
  • 2     mongo   mongodump    mongofiles   mongorestore  mongosniff
  • dump  mongod  mongoexport  mongoimport  mongos     test
  MongoDB的数据恢复工具 mongorestore

查看test库中的表

  • > show collections
  • system.indexes
  • User
  删除user表

  • > db.user.drop();
  • True

  • > show collections
  • System.indexes
  现在利用mongorestore表恢复刚才利用 mongodump备份的数据

  • [falcon@www.fwphp.cn  ~/mongodb/bin]$ ./mongorestore --help
  • usage: ./mongorestore [options] [directory or filename to restore from]
  • 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)

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

  •          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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-137792-1-1.html 上篇帖子: node.js连接mongodb数据库警告:(Please ensure that you set the default write concern) 下篇帖子: MongoDB数据库文档大全(第1-3讲)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表