MongoDB入门学习(一):MongoDB的安装和管理

        曾经用MySQL数据库,整天都是写大堆大堆的SQL语句。要记住这些SQLkeyword都要花好几天时间,写的蛋都爆了,当接触到MongoDB的时候,发现不用写SQL,瞬间认为高大上,瞬间产生了学习使用它的冲动。

1.MongoDB简单介绍

        MongoDB是一种强大,灵活。可扩展的数据存储方式。

它扩展了关系型数据库的众多实用功能,如辅助索引。范围查询和排序。MongoDB的功能非常丰富,比方内置的对MapReduce式聚合的支持。以及对地理空间索引的支持。

还有非常多非常多的特点。。。

        对于入门级别的人来说。上面说的这些都是浮云,我如今体会不到它的容量。也体会不到它的横向扩展,更体会不到它的速率,这些都是当我们玩到一定的境地才会关心的问题。

我单纯认为它的优点就是很easy上手。提供了一系列的API,不用写SQL语句。

至于它和关系型数据库有什么差别。有哪些优点或者哪些缺点须要如何改进都是以后的事了。

2.MongoDB的安装

        mongodb的官网就有下载,依据系统windows还是linux还是别的下载32位还是64位的,然后解压安装。

我是在Linux上安装的。刚開始是在自己的虚拟机上通过root用yum安装的,后来是通过secureCRT连接别的server在自己的用户上安装学习的,这样就能够玩自己的mongodb不至于弄挂server上面的。可是这样不能通过yum了,源代码安装貌似又有非常多的软件依赖,所以就在官网上下载了一个linux版的,然后通过SFTP上传到server上解压后直接使用。

3.MongoDB的管理

        解压完之后进入bin文件夹,里面都是一些可运行文件,mongo,mongod。mongodump,mongoexport等。后面再说它们的作用吧。

        1).启动和停止MongoDB

           通过运行mongod来启动MongoDBserver,mongod有非常多的配置启动选项的,能够通过mongod --help来查看,当中有一些基本的选项:

           --dbpath:指定数据文件夹,默认是/data/db/。每一个mongod进程都须要独立的文件夹,启动mongod时就会在数据文件夹中创建mongod.lock文件,防止其它mongod进程使用该数据文件夹。

           --port:指定server监听的端口,默认是27017。

           --fork:以守护进程的方式执行MongoDB。

           --logpath:指定日志输出路径,假设不指定则会在终端输出。每次启动都会覆盖原来的日志,假设不想覆盖就要用--logappend选项。

           --config:指定配置文件,载入命令行未指定的各种选项。我们能够讲我们须要用到的选项写在某个文件里,然后通过该选项来指定这个文件就不必每次启动mongod时都要写。

           比方我的配置文件mongodb.conf有例如以下配置:

port = 9352
#fork = true              #为凝视
#logpath = mongodb.log
dbpath = data/db

           运行mongod启动MongoDBserver指定配置文件:

[tp0352@server0 bin]$ ./mongod --config mongodb.conf 
2014-06-05T17:11:13.118+0800 [initandlisten] MongoDB starting : pid=18077 port=9352 dbpath=data/db 64-bit host=server0.169
2014-06-05T17:11:13.119+0800 [initandlisten] db version v2.6.1
2014-06-05T17:11:13.119+0800 [initandlisten] git version: 4b95b086d2374bdcfcdf2249272fb552c9c726e8
2014-06-05T17:11:13.119+0800 [initandlisten] build info: Linux build14.nj1.10gen.cc 2.6.32-431.3.1.el6.x86_64 #1 SMP Fri Jan 3 21:39:27 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49
2014-06-05T17:11:13.119+0800 [initandlisten] allocator: tcmalloc
2014-06-05T17:11:13.119+0800 [initandlisten] options: { config: "mongodb.conf", net: { port: 9352 }, storage: { dbPath: "data/db" } }
2014-06-05T17:11:13.246+0800 [initandlisten] journal dir=data/db/journal
2014-06-05T17:11:13.246+0800 [initandlisten] recover : no journal files present, no recovery needed
2014-06-05T17:11:15.333+0800 [initandlisten] preallocateIsFaster=true 20.74
2014-06-05T17:11:17.692+0800 [initandlisten] preallocateIsFaster=true 13.72
2014-06-05T17:11:20.858+0800 [initandlisten] preallocateIsFaster=true 23.86
2014-06-05T17:11:20.858+0800 [initandlisten] preallocateIsFaster check took 7.612 secs
2014-06-05T17:11:20.858+0800 [initandlisten] preallocating a journal file data/db/journal/prealloc.0
2014-06-05T17:11:23.121+0800 [initandlisten]            File Preallocator Progress: 492830720/1073741824        45%
2014-06-05T17:11:26.424+0800 [initandlisten]            File Preallocator Progress: 681574400/1073741824        63%
2014-06-05T17:11:29.004+0800 [initandlisten]            File Preallocator Progress: 964689920/1073741824        89%
2014-06-05T17:11:34.558+0800 [initandlisten] preallocating a journal file data/db/journal/prealloc.1
2014-06-05T17:11:37.089+0800 [initandlisten]            File Preallocator Progress: 524288000/1073741824        48%
2014-06-05T17:11:40.090+0800 [initandlisten]            File Preallocator Progress: 807403520/1073741824        75%
2014-06-05T17:11:43.063+0800 [initandlisten]            File Preallocator Progress: 1017118720/1073741824       94%
2014-06-05T17:11:48.020+0800 [initandlisten] preallocating a journal file data/db/journal/prealloc.2
2014-06-05T17:11:51.040+0800 [initandlisten]            File Preallocator Progress: 576716800/1073741824        53%
2014-06-05T17:11:54.039+0800 [initandlisten]            File Preallocator Progress: 807403520/1073741824        75%
2014-06-05T17:11:57.026+0800 [initandlisten]            File Preallocator Progress: 1069547520/1073741824       99%
2014-06-05T17:12:01.985+0800 [FileAllocator] allocating new datafile data/db/local.ns, filling with zeroes...
2014-06-05T17:12:01.985+0800 [FileAllocator] creating directory data/db/_tmp
2014-06-05T17:12:02.285+0800 [FileAllocator] done allocating datafile data/db/local.ns, size: 16MB,  took 0.167 secs
2014-06-05T17:12:02.315+0800 [FileAllocator] allocating new datafile data/db/local.0, filling with zeroes...
2014-06-05T17:12:02.413+0800 [FileAllocator] done allocating datafile data/db/local.0, size: 64MB,  took 0.097 secs
2014-06-05T17:12:02.434+0800 [initandlisten] build index on: local.startup_log properties: { v: 1, key: { _id: 1 }, name: "_id_", ns: "local.startup_log" }
2014-06-05T17:12:02.434+0800 [initandlisten]     added index to empty collection
2014-06-05T17:12:02.456+0800 [initandlisten] command local.$cmd command: create { create: "startup_log", size: 10485760, capped: true } ntoreturn:1 keyUpdates:0 numYields:0  reslen:37 494ms
2014-06-05T17:12:02.457+0800 [initandlisten] waiting for connections on port 9352

           启动MongoDBserver成功,监听port9352,等待client来连接。假设指定日志文件,这些日志就会被输出到指定的日志文件。假设设置为守护进程,就会创建一个子进程。当MongoDBserver启动完毕后父进程就会退出。

           让MongoDB稳妥的停下来非常重要。由于可能有的数据还在缓存没写入磁盘,稳妥停止是先让数据写进磁盘然后再结束MongoDB进程。能够直接用ctrl+c来停止MongoDBserver。也能够通过client来。mongo是一个javascript shell,启动它的时候会自己主动连接MongoDBserver,所以mongo也是一个MongoDBclient。它能够执行不论什么javascript程序。也能够操作数据库。

以下来看一下mongo停止MongoDBserver:

[tp0352@server0 bin]$ ./mongo --port 9352
MongoDB shell version: 2.6.1
connecting to: 127.0.0.1:9352/test
> show dbs
admin  (empty)
local  0.078GB
test   (empty)
> use admin
switched to db admin
> db.shutdownServer()
2014-06-05T17:21:59.263+0800 DBClientCursor::init call() failed
server should be down...
2014-06-05T17:21:59.265+0800 trying reconnect to 127.0.0.1:9352 (127.0.0.1) failed
2014-06-05T17:21:59.266+0800 warning: Failed to connect to 127.0.0.1:9352, reason: errno:111 Connection refused
2014-06-05T17:21:59.266+0800 reconnect 127.0.0.1:9352 (127.0.0.1) failed failed couldn't connect to server 127.0.0.1:9352 (127.0.0.1), connection attempt failed
> exit
bye

           从上面能够看出,我们连接到了本地9352porttest数据库。admin就是一个root数据库,这个数据库是用来管理整个MongoDB的,不是不论什么人都能够停止MongoDBserver的,所以要使用admin来运行shutdownServer()来停止。

        2).安全和认证

           上面通过mongo这个client来连接MongoDBserver。没有不论什么的安全认证,也就是说不论什么人都能够连上去,当然能够在一个可信环境中运行它,保证仅仅有可信的机器才干訪问它,也能够对单个连接的认证。每一个MongoDB的数据库都能够有很多用户,假设开启了安全性检查。则仅仅有数据库认证用户才干运行相关的操作。admin的用户能够对不论什么数据库进行读写操作,其它数据库的用户仅仅能运行相关权限的操作。

           开启安全检查前,先创建几个用户:

> use admin
switched to db admin
> db.addUser("tp", "12345")
WARNING: The 'addUser' shell helper is DEPRECATED. Please use 'createUser' instead
Successfully added user: { "user" : "tp", "roles" : [ "root" ] }
> use test
switched to db test
> db.addUser("test1", "12345", true)
WARNING: The 'addUser' shell helper is DEPRECATED. Please use 'createUser' instead
Successfully added user: { "user" : "test1", "roles" : [ "read" ] }
> db.addUser("test2", "12345")
WARNING: The 'addUser' shell helper is DEPRECATED. Please use 'createUser' instead
Successfully added user: { "user" : "test2", "roles" : [ "dbOwner" ] }
> use admin
switched to db admin
> show collections
system.indexes
system.users
system.version
> db.system.users.find()
{ "_id" : "admin.tp", "user" : "tp", "db" : "admin", "credentials" : { "MONGODB-CR" : "e4aafd1c8d19d9e490192fe5bf43ffe0" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "test.test1", "user" : "test1", "db" : "test", "credentials" : { "MONGODB-CR" : "2da1438b5a04dd46cfdf97c40a3c6d71" }, "roles" : [ { "role" : "read", "db" : "test" } ] }
{ "_id" : "test.test2", "user" : "test2", "db" : "test", "credentials" : { "MONGODB-CR" : "4accbd2cb1dce25ed8b3b162103b0b87" }, "roles" : [ { "role" : "dbOwner", "db" : "test" } ] }

           在admin中加入了一个用户tp。在test数据库中加入了两个用户test1和test2,addUser()有三个參数。第一个是username,第二个是password,第三个是仅仅读状态,设置true为仅仅读。从用户集合system.users能够看出,tp是admin数据库中的超级用户。有root权限,test1仅仅有read权限,test2是dbOwner,能够读也能够写。addUser还能改动用户password和仅仅读状态。以下重新启动MongoDBserver,加入--auth命令选项来开启安全检查。然后再通过mongo来连接:

> show dbs
2014-06-05T17:59:57.519+0800 listDatabases failed:{
        "ok" : 0,
        "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
        "code" : 13
} at src/mongo/shell/mongo.js:47
> use test
switched to db test
> db.auth("test1", "12345")
1
> show collections
people
system.indexes
> db.people.find()
{ "_id" : ObjectId("53903f7af73bb0df22f8e4a6"), "name" : "Mary", "age" : 10 }
> db.people.insert({"name" : "join", "age" : 20})
WriteResult({
        "writeError" : {
                "code" : 13,
                "errmsg" : "not authorized on test to execute command { insert: "people", documents: [ { _id: ObjectId('53903fd6959e902814f56d8c'), name: "join", age: 20.0 } ], ordered: true }"
        }
})
> db.auth("test2", "12345")
1
> db.people.find()
{ "_id" : ObjectId("53903f7af73bb0df22f8e4a6"), "name" : "Mary", "age" : 10 }
> db.people.insert({"name" : "join", "age" : 20})
WriteResult({ "nInserted" : 1 })
> use admin
switched to db admin
> db.auth("tp", "12345")
1
> show dbs
admin  0.078GB
local  0.078GB
test   0.078GB

           连接到MongoDBserver后没有进行用户认证。所以什么都不能干,当使用test数据库并进行用户认证后,就能够查看test库中的集合,由于test1仅仅能读不能写,所以find能够成功而insert失败,test2既能读也能写,使用admin数据库进行用户认证后就能够查看全部的数据库列表。事实上这种认证用途不是非常大,仅仅是一种方式而已,最安全的方式还是限制訪问。

        3).数据备份

           ①.数据文件备份

              最简单的备份就是数据文件的备份,就是直接赋值data/db这个文件夹。由于我们前面已经指定了数据文件夹就是data/db,那么MongoDB多有的数据都在这里,可是有个问题就是最新的数据还在缓存中,没用同步到磁盘。能够先停止shutdownServer()再备份。

可是这样会影响MongoDB正常的工作。

           ②.mongodump和mongorestore

              bin中还有mongodump和mongorestore两个可执行文件,这个是对MongoDB的某个数据库进行备份,能够在MongoDB正在执行时进行备份。比方备份test数据库。然后将备份的数据库文件再倒入别的MongoDBserver上。

这样的备份的方式备份的不是最新数据,仅仅是已经写入MongoDB中的数据,可能还有的数据在缓存中没有写入,那么这部分数据就是备份不到的。mongodump和mongorestore也能够通过--help查询全部选项。

[tp0352@server0 bin]$ ./mongodump --port 9352 -d test -o test_data
connected to: 127.0.0.1
2014-06-05T19:00:03.381+0800 DATABASE: test      to     test_data/test
2014-06-05T19:00:03.411+0800    test.system.indexes to test_data/test/system.indexes.bson
2014-06-05T19:00:03.426+0800             1 documents
2014-06-05T19:00:03.426+0800    test.test to test_data/test/test.bson
2014-06-05T19:00:03.463+0800             1 documents
2014-06-05T19:00:03.464+0800    Metadata for test.test to test_data/test/test.metadata.json

              -d是指定数据库,-o是输出备份文件,上面将test数据库备份为test_data文件。

[tp0352@server0 bin]$ ./mongorestore --port 9352 -d temple --drop test_data/test/
connected to: 127.0.0.1:9352
2014-06-05T19:05:53.454+0800 test_data/test/people.bson
2014-06-05T19:05:53.454+0800    going into namespace [temple.people]
2014-06-05T19:05:53.454+0800     dropping
2 objects found
2014-06-05T19:05:53.454+0800    Creating index: { key: { _id: 1 }, name: "_id_", ns: "temple.people" }
[tp0352@server0 bin]$ ./mongo --port 9352
MongoDB shell version: 2.6.1
connecting to: 127.0.0.1:9352/test
> show dbs
admin   0.078GB
local   0.078GB
temple  0.078GB
test    0.078GB

              这里将上面备份出来的test数据库如今又一次导入到temple数据库。--drop代表假设有了temple数据库则将当中的全部集合删除。不指定就会和原来temple中的集合合并。

           ③.mongoexport和mongoimport

              上面讲到mongodump和mongorestore是备份某个数据库的。那么mongoexport和mongoimport就是备份某个数据库中的某个表,相同能够通过--help来查看全部的选项,当然mongoexport也是能够不统计的备份,可是却不一定是最新数据。

[tp0352@server0 bin]$ ./mongoexport --port 9352 -d test -c people -o prson 
connected to: 127.0.0.1:9352
exported 2 records
[tp0352@server0 bin]$ cat prson 
{ "_id" : { "$oid" : "53903f7af73bb0df22f8e4a6" }, "name" : "Mary", "age" : 10 }
{ "_id" : { "$oid" : "53903ff6959e902814f56d8d" }, "name" : "join", "age" : 20 }
[tp0352@server0 bin]$ ./mongoimport --port 9352 -d temple -c user prson 
connected to: 127.0.0.1:9352
2014-06-05T19:14:00.555+0800 imported 2 objects
[tp0352@server0 bin]$ ./mongo --port 9352
MongoDB shell version: 2.6.1
connecting to: 127.0.0.1:9352/test
> use temple
switched to db temple
> show collections
system.indexes
user
> db.user.find()
{ "_id" : ObjectId("53903f7af73bb0df22f8e4a6"), "name" : "Mary", "age" : 10 }
{ "_id" : ObjectId("53903ff6959e902814f56d8d"), "name" : "join", "age" : 20 }

              -c表示collection集合,上面将test库中的people集合备份出来为prson文件,然后再导入到temple库中的user集合。

        ④.fsync和锁

              mongodump和mongoexport对都能够不停MongoDBserver来进行备份,可是却失去了获取实时数据的能力。而fsync命令也能在不停MongoDB的情况下备份实时数据,它的实现事实上就是上锁。阻止对数据库的写入操作,然后将缓冲区的数据写入磁盘。备份后再解锁。在这个期间,不论什么对数据库的写入操作都会堵塞。直到锁被释放。

> db.runCommand({"fsync" : 1, "lock" : 1})
{
        "info" : "now locked against writes, use db.fsyncUnlock() to unlock",
        "seeAlso" : "http://dochub.mongodb.org/core/fsynccommand",
        "ok" : 1
}
>
>在这之间进行备份,运行不论什么insert操作都会堵塞
>
> db.fsyncUnlock()
{ "ok" : 1, "info" : "unlock completed" }

              我认为事实上实时也是相对的。将数据库锁住不让写。那么最新的数据还是没备份到。

原文地址:https://www.cnblogs.com/gavanwanggw/p/6918876.html