现在的位置: 首页 > 综合 > 正文

Mongo初体验

2013年06月02日 ⁄ 综合 ⁄ 共 22906字 ⁄ 字号 评论关闭

一、下载安装

安装Mongo数据库:2.0.7(支持win32)

  在发布本文的时间官方提供的最新版本是:1.6.5 ,如果不做特殊声明,本教程所用的版本将会是这个版本。

  1. 第一步:下载安装包:官方下载地址←单击此处,如果是win系统,注意是64位还是32位版本的,请选择正确的版本。
  2. 第二步:新建目录“D:\MongoDB”,解压下载到的安装包,找到bin目录下面全部.exe文件,拷贝到刚创建的目录下。
  3. 第三步:在“D:\MongoDB”目录下新建“data”文件夹,它将会作为数据存放的根文件夹。

  配置Mongo服务端:

  打开CMD窗口,按照如下方式输入命令:
  > d:
  > cd D:\MongoDB
  > mongod --dbpath D:\MongoDB\data

  配置成功后会看到如下画面:
 

  在浏览器输入:http://localhost:27017/,可以看到如下提示:
You are trying to access MongoDB on the native driver port. For http diagnostic access, add 1000 to the port number

  如此,MongoDB数据库服务已经成功启动了。

 

二、在Windows中注册MongoDB服务

MongoDB以Windows服务安装(Windows 32-bit)

一.准备工作

1:下载:  http://www.mongodb.org/downloads 选择Windows 32-bit

2:解压到ZIP到 D:\Mongodb  ,在此目录下再建立2个目录  D:\Mongodb\dbD:\Mongodb\logs 

D:\Mongodb\logs 新建MongoDB.log文件

二.安装

1.开始--运行--cmd

2.cd D:\Mongodb\bin

3.D:\Mongodb\bin>mongod --logpath D:\MongoDB\logs\MongoDB.log --logappend --dbpath D:\MongoDB\db --directoryperdb --serviceName MongoDB
--install

如果安装成功,显示下面文字

all output going to: D:\MongoDB\logs\MongoDB.log
Creating service MongoDB.
Service creation successful.
Service can be started from the command line via 'net start "MongoDB"'.

强调

1:log一定要指定一个xxx.log文件(文件不存在也要这么写,会自动创建,写成这样是不可以的--logpath d:\mongodb\logs)

2:serviceName的N字母要大写

注意:这条命令要到MongoDB的bin目录下运行,刚开始的时候,我就直接在D:\下运行,结果服务的可执行目录为【"D:\mongod" --logpath  "D:\MongoDB\logs\MongoDB.log"  --logappend  --dbpath  "D:\MongoDB\db"  --directoryperdb  --service 】,肯定是不对的。

该命令行指定了日志文件:D:\MongoDB\logs\MongoDB.log,日志是以追加的方式输出的;

数据文件目录:D:\MongoDB\db,并且参数--directoryperdb说明每个DB都会新建一个目录;

Windows服务的名称:MongoDB;

以上的三个参数都是可以根据自己的情况而定的,呵呵。

最后是安装参数:--install,与之相对的是--remove

启动MongoDB:net start MongoDB

停止MongoDB:net stop MongoDB

 

三、常用命令行操作

MongoDB是一个NoSQL数据库系统:一个数据库可以包含多个集合(Collection),每个集合对应于关系数据库中的表;而每个集合中可以存储一组由列标识的记录,列是可以自由定义的,非常灵活,由一组列标识的实体的集合对应于关系数据库表中的行。下面通过熟悉MongoDB的基本管理命令,来了解MongoDB提供的DBMS的基本功能和行为。

MongoDB命令帮助系统

在安装MongoDB后,启动服务器进程(mongod),可以通过在客户端命令mongo实现对MongoDB的管理和监控。看一下MongoDB的命令帮助系统:

  1. root@dev2:~# mongo  
  2. MongoDB shell version: 1.8.3  
  3. connecting to: test  
  4. > help  
  5.         db.help()                    help on db methods  
  6.         db.mycoll.help()             help on collection methods  
  7.         rs.help()                    help on replica set methods  
  8.         help connect                 connecting to a db help  
  9.         help admin                   administrative help  
  10.         help misc                    misc things to know  
  11.         help mr                      mapreduce help  
  12.   
  13.         show dbs                     show database names  
  14.         show collections             show collections in current database  
  15.         show users                   show users in current database  
  16.         show profile                 show most recent system.profile entries with time >= 1ms  
  17.         use <db_name>                set current database  
  18.         db.foo.find()                list objects in collection foo  
  19.         db.foo.find( { a : 1 } )     list objects in foo where a == 1  
  20.         it                           result of the last line evaluated; use to further iterate  
  21.         DBQuery.shellBatchSize = x   set default number of items to display on shell  
  22.         exit                         quit the mongo shell  

这是MongoDB最顶层的命令列表,主要告诉我们管理数据库相关的一些抽象的范畴:数据库操作帮助、集合操作帮助、管理帮助。如果你想了解数据库操作更详细的帮助命令,可以直接使用db.help(),如下所示:

  1. > db.help()  
  2. DB methods:  
  3.         db.addUser(username, password[, readOnly=false])  
  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() - deprecated  
  21.         db.getProfilingStatus() - returns if profiling is on and slow threshold   
  22.         db.getReplicationInfo()  
  23.         db.getSiblingDB(name) get the db at the same server as this one  
  24.         db.isMaster() check replica primary status  
  25.         db.killOp(opid) kills the current operation in the db  
  26.         db.listCommands() lists all the db commands  
  27.         db.printCollectionStats()  
  28.         db.printReplicationInfo()  
  29.         db.printSlaveReplicationInfo()  
  30.         db.printShardingStatus()  
  31.         db.removeUser(username)  
  32.         db.repairDatabase()  
  33.         db.resetError()  
  34.         db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }  
  35.         db.serverStatus()  
  36.         db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all  
  37.         db.shutdownServer()  
  38.         db.stats()  
  39.         db.version() current version of the server  
  40.         db.getMongo().setSlaveOk() allow queries on a replication slave server  

对数据库进行管理和操作的基本命令,可以从上面获取到。如果想要得到更多,而且每个命令的详细用法,可以使用上面列出的db.listCommands()查询。

另一个比较基础的是对指定数据库的集合进行操作、管理和监控,可以通过查询db.mycoll.help()获取到:

  1. > db.mycoll.help()  
  2. DBCollection help  
  3.         db.mycoll.find().help() - show DBCursor help  
  4.         db.mycoll.count()  
  5.         db.mycoll.dataSize()  
  6.         db.mycoll.distinct( key ) - eg. db.mycoll.distinct( 'x' )  
  7.         db.mycoll.drop() drop the collection  
  8.         db.mycoll.dropIndex(name)  
  9.         db.mycoll.dropIndexes()  
  10.         db.mycoll.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups  
  11.         db.mycoll.reIndex()  
  12.         db.mycoll.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.  
  13.                                                       e.g. db.mycoll.find( {x:77} , {name:1, x:1} )  
  14.         db.mycoll.find(...).count()  
  15.         db.mycoll.find(...).limit(n)  
  16.         db.mycoll.find(...).skip(n)  
  17.         db.mycoll.find(...).sort(...)  
  18.         db.mycoll.findOne([query])  
  19.         db.mycoll.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )  
  20.         db.mycoll.getDB() get DB object associated with collection  
  21.         db.mycoll.getIndexes()  
  22.         db.mycoll.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )  
  23.         db.mycoll.mapReduce( mapFunction , reduceFunction , <optional params> )  
  24.         db.mycoll.remove(query)  
  25.         db.mycoll.renameCollection( newName , <dropTarget> ) renames the collection.  
  26.         db.mycoll.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name  
  27.         db.mycoll.save(obj)  
  28.         db.mycoll.stats()  
  29.         db.mycoll.storageSize() - includes free space allocated to this collection  
  30.         db.mycoll.totalIndexSize() - size in bytes of all the indexes  
  31.         db.mycoll.totalSize() - storage allocated for all data and indexes  
  32.         db.mycoll.update(query, object[, upsert_bool, multi_bool])  
  33.         db.mycoll.validate() - SLOW  
  34.         db.mycoll.getShardVersion() - only for use with sharding  

有关数据库和集合管理的相关命令,是最基础和最常用的,如集合查询、索引操作等。

基本命令及实例

下面通过实际的例子来演示一些常见的命令:

(一)基本命令

1、show dbs

显示当前数据库服务器上的数据库
2、use pagedb
 切换到指定数据库pagedb的上下文,可以在此上下文中管理pagedb数据库以及其中的集合等
3、show collections
显示数据库中所有的集合(collection)
4、db.serverStatus()  
查看数据库服务器的状态。示例如下所示:
  1. {  
  2.         "host" : "dev2",  
  3.         "version" : "1.8.3",  
  4.         "process" : "mongod",  
  5.         "uptime" : 845446,  
  6.         "uptimeEstimate" : 839192,  
  7.         "localTime" : ISODate("2011-12-27T04:03:12.512Z"),  
  8.         "globalLock" : {  
  9.                 "totalTime" : 845445636925,  
  10.                 "lockTime" : 13630973982,  
  11.                 "ratio" : 0.016122827283818857,  
  12.                 "currentQueue" : {  
  13.                         "total" : 0,  
  14.                         "readers" : 0,  
  15.                         "writers" : 0  
  16.                 },  
  17.                 "activeClients" : {  
  18.                         "total" : 0,  
  19.                         "readers" : 0,  
  20.                         "writers" : 0  
  21.                 }  
  22.         },  
  23.         "mem" : {  
  24.                 "bits" : 64,  
  25.                 "resident" : 12208,  
  26.                 "virtual" : 466785,  
  27.                 "supported" : true,  
  28.                 "mapped" : 466139  
  29.         },  
  30.         "connections" : {  
  31.                 "current" : 27,  
  32.                 "available" : 792  
  33.         },  
  34.         "extra_info" : {  
  35.                 "note" : "fields vary by platform",  
  36.                 "heap_usage_bytes" : 70895216,  
  37.                 "page_faults" : 17213898  
  38.         },  
  39.         "indexCounters" : {  
  40.                 "btree" : {  
  41.                         "accesses" : 4466653,  
  42.                         "hits" : 4465526,  
  43.                         "misses" : 1127,  
  44.                         "resets" : 0,  
  45.                         "missRatio" : 0.00025231420484197006  
  46.                 }  
  47.         },  
  48.         "backgroundFlushing" : {  
  49.                 "flushes" : 14090,  
  50.                 "total_ms" : 15204393,  
  51.                 "average_ms" : 1079.0910574875797,  
  52.                 "last_ms" : 669,  
  53.                 "last_finished" : ISODate("2011-12-27T04:02:28.713Z")  
  54.         },  
  55.         "cursors" : {  
  56.                 "totalOpen" : 3,  
  57.                 "clientCursors_size" : 3,  
  58.                 "timedOut" : 53  
  59.         },  
  60.         "network" : {  
  61.                 "bytesIn" : 63460818650,  
  62.                 "bytesOut" : 763926196104,  
  63.                 "numRequests" : 67055921  
  64.         },  
  65.         "opcounters" : {  
  66.                 "insert" : 7947057,  
  67.                 "query" : 35720451,  
  68.                 "update" : 16263239,  
  69.                 "delete" : 154,  
  70.                 "getmore" : 91707,  
  71.                 "command" : 68520  
  72.         },  
  73.         "asserts" : {  
  74.                 "regular" : 0,  
  75.                 "warning" : 1,  
  76.                 "msg" : 0,  
  77.                 "user" : 7063866,  
  78.                 "rollovers" : 0  
  79.         },  
  80.         "writeBacksQueued" : false,  
  81.         "ok" : 1  
  82. }  

有时,通过查看数据库服务器的状态,可以判断数据库是否存在问题,如果有问题,如数据损坏,可以及时执行修复。

5、查询指定数据库统计信息
use fragment
db.stats()
查询结果示例如下所示:
  1. > db.stats()  
  2. {  
  3.         "db" : "fragment",  
  4.         "collections" : 12,  
  5.         "objects" : 384553,  
  6.         "avgObjSize" : 3028.40198360174,  
  7.         "dataSize" : 1164581068,  
  8.         "storageSize" : 1328351744,  
  9.         "numExtents" : 109,  
  10.         "indexes" : 10,  
  11.         "indexSize" : 16072704,  
  12.         "fileSize" : 4226809856,  
  13.         "ok" : 1  
  14. }  

显示fragment数据库的统计信息。

6、查询指定数据库包含的集合名称列表
db.getCollectionNames()
结果如下所示:
  1. > db.getCollectionNames()  
  2. [  
  3.         "17u",  
  4.         "baseSe",  
  5.         "bytravel",  
  6.         "daodao",  
  7.         "go2eu",  
  8.         "lotour",  
  9.         "lvping",  
  10.         "mafengwo",  
  11.         "sina",  
  12.         "sohu",  
  13.         "system.indexes"  
  14. ]  

(二)基本DDL和DML

1、创建数据库

如果你习惯了关系型数据库,你可能会寻找相关的创建数据库的命令。在MongoDB中,你可以直接通过use dbname来切换到这个数据库上下文下面,系统会自动延迟创建该数据库,例如:
  1. > show dbs  
  2. admin   0.03125GB  
  3. local   (empty)  
  4. pagedb  0.03125GB  
  5. test    0.03125GB  
  6. > use LuceneIndexDB  
  7. switched to db LuceneIndexDB  
  8. > show dbs  
  9. admin   0.03125GB  
  10. local   (empty)  
  11. pagedb  0.03125GB  
  12. test    0.03125GB  
  13. > db  
  14. LuceneIndexDB  
  15. > db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'})  
  16. > show dbs  
  17. LuceneIndexDB   0.03125GB  
  18. admin   0.03125GB  
  19. local   (empty)  
  20. pagedb  0.03125GB  
  21. test    0.03125GB  
  22. >  
可见,在use指定数据库后,并且向指定其中的一个集合并插入数据后,数据库和集合都被创建了。
2、删除数据库
直接使用db.dropDatabase()即可删除数据库。
3、创建集合
可以使用命令db.createCollection(name, { size : ..., capped : ..., max : ... } )创建集合,示例如下所示:
  1. > db.createCollection('replicationColletion', {'capped':true, 'size':10240, 'max':17855200})  
  2. { "ok" : 1 }  
  3. > show collections  
  4. replicationColletion  
  5. storeCollection  
  6. system.indexes  

4、删除集合

删除集合,可以执行db.mycoll.drop()。

5、插入更新记录

直接使用集合的save方法,如下所示:

  1. > <EM>db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'})</EM>  

更新记录,使用save会将原来的记录值进行覆盖实现记录更新。

6、查询一条记录

使用findOne()函数,参数为查询条件,可选,系统会随机查询获取到满足条件的一条记录(如果存在查询结果数量大于等于1)示例如下所示:

  1. > db.storeCollection.findOne({'version':'3.5'})  
  2. {  
  3.         "_id" : ObjectId("4ef970f23c1fc4613425accc"),  
  4.         "version" : "3.5",  
  5.         "segment" : "e3ol6"  
  6. }  

7、查询多条记录

使用find()函数,参数指定查询条件,不指定条件则查询全部记录。

8、删除记录

使用集合的remove()方法,参数指定为查询条件,示例如下所示:

  1. > db.storeCollection.remove({'version':'3.5'})  
  2. > db.storeCollection.findOne()  
  3. null  

9、创建索引

可以使用集合的ensureIndex(keypattern[,options])方法,示例如下所示:

  1. > use pagedb  
  2. switched to db pagedb  
  3. > db.page.ensureIndex({'title':1, 'url':-1})  
  4. > db.system.indexes.find()  
  5. { "name" : "_id_", "ns" : "pagedb.page", "key" : { "_id" : 1 }, "v" : 0 }  
  6. { "name" : "_id_", "ns" : "pagedb.system.users", "key" : { "_id" : 1 }, "v" : 0}  
  7. { "_id" : ObjectId("4ef977633c1fc4613425accd"), "ns" : "pagedb.page", "key" : {"title" : 1, "url" : -1 }, "name" : "title_1_url_-1", "v" : 0 }  

上述,ensureIndex方法参数中,数字1表示升序,-1表示降序。

使用db.system.indexes.find()可以查询全部索引。

10、查询索引

我们为集合建立的索引,那么可以通过集合的getIndexes()方法实现查询,示例如下所示:

  1. > db.page.getIndexes()  
  2. [  
  3.         {  
  4.                 "name" : "_id_",  
  5.                 "ns" : "pagedb.page",  
  6.                 "key" : {  
  7.                         "_id" : 1  
  8.                 },  
  9.                 "v" : 0  
  10.         },  
  11.         {  
  12.                 "_id" : ObjectId("4ef977633c1fc4613425accd"),  
  13.                 "ns" : "pagedb.page",  
  14.                 "key" : {  
  15.                         "title" : 1,  
  16.                         "url" : -1  
  17.                 },  
  18.                 "name" : "title_1_url_-1",  
  19.                 "v" : 0  
  20.         }  
  21. ]  

当然,如果需要查询系统中全部的索引,可以使用db.system.indexes.find()函数。
11、删除索引

删除索引给出了两个方法:

  1. db.mycoll.dropIndex(name)  
  2. db.mycoll.dropIndexes()  

第一个通过指定索引名称,第二个删除指定集合的全部索引。

12、索引重建

可以通过集合的reIndex()方法进行索引的重建,示例如下所示:

  1. > db.page.reIndex()  
  2. {  
  3.         "nIndexesWas" : 2,  
  4.         "msg" : "indexes dropped for collection",  
  5.         "ok" : 1,  
  6.         "nIndexes" : 2,  
  7.         "indexes" : [  
  8.                 {  
  9.                         "name" : "_id_",  
  10.                         "ns" : "pagedb.page",  
  11.                         "key" : {  
  12.                                 "_id" : 1  
  13.                         },  
  14.                         "v" : 0  
  15.                 },  
  16.                 {  
  17.                         "_id" : ObjectId("4ef977633c1fc4613425accd"),  
  18.                         "ns" : "pagedb.page",  
  19.                         "key" : {  
  20.                                 "title" : 1,  
  21.                                 "url" : -1  
  22.                         },  
  23.                         "name" : "title_1_url_-1",  
  24.                         "v" : 0  
  25.                 }  
  26.         ],  
  27.         "ok" : 1  
  28. }  

13、统计集合记录数

use fragment

db.baseSe.count()
统计结果,如下所示:

  1. > use fragment  
  2. switched to db fragment  
  3. > db.baseSe.count()  
  4. 36749  

上述统计了数据库fragment的baseSe集合中记录数。
14、查询并统计结果记录数

use fragment
db.baseSe.find().count()

find()可以提供查询参数,然后查询并统计结果,如下所示:

  1. > use fragment  
  2. switched to db fragment  
  3. > db.baseSe.find().count()  
  4. 36749  

上述执行先根据查询条件查询结果,然后统计了查询数据库fragment的baseSe结果记录集合中记录数。

15、查询指定数据库的集合当前可用的存储空间

use fragment
> db.baseSe.storageSize()
142564096

16、查询指定数据库的集合分配的存储空间

> db.baseSe.totalSize()

144096000

上述查询结果中,包括为集合(数据及其索引存储)分配的存储空间。

(三)启动与终止

1、正常启动
mongod --dbpath /usr/mongo/data --logfile /var/mongo.log
说明:
指定数据存储目录和日志目录,如果采用安全认证模式,需要加上--auth选项,如:
mongod --auth --dbpath /usr/mongo/data --logfile /var/mongo.log 
2、以修复模式启动
mongod --repair
以修复模式启动数据库。
实际很可能数据库数据损坏或数据状态不一致,导致无法正常启动MongoDB服务器,根据启动信息可以看到需要进行修复。或者执行:
mongod -f /etc/mongodb.conf --repair
3、终止服务器进程
db.shutdownServer()
终止数据库服务器进程。或者,可以直接kill掉mongod进程即可。

(四)安全管理

    1、以安全认证模式启动

    mongod --auth --dbpath /usr/mongo/data --logfile /var/mongo.log
    使用--auth选项启动mongod进程即可启用认证模式。
    或者,也可以修改/etc/mongodb.conf,设置auth=true,重启mongod进程。
    2、添加用户
    db.addUser("admin", ",%F23_kj~00Opoo0+\/")
    添加数据库用户,添加成功,则显示结果如下所示:

    抱歉!评论已关闭.