欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

monogdb之数据备份恢复与数据的导入导出

程序员文章站 2022-04-19 11:45:44
...

### 备份方式和恢复方式 备份全部数据库 mkdir /bak mongodump 备份指定数据库 mkidr /bak mongodump -d admin 备份一个数据库中的某个集合 mkdir /bak mongodump -d admin -c student 恢复全部数据库 mongorestore --drop # --drop是为了防止数据重复 恢复

### 备份方式和恢复方式

备份全部数据库

mkdir /bak

mongodump

备份指定数据库

mkidr /bak

mongodump -d admin

备份一个数据库中的某个集合

mkdir /bak

mongodump -d admin -c student

恢复全部数据库

mongorestore --drop # --drop是为了防止数据重复

恢复某个数据库

mongorestore -d dbname --drop

恢复某个数据库的某个集合

mongorestore -d dbname -c student --drop

异机数据恢复

mongorestore -h host -d dbname /path/sourcefile # 注意这里要使用dump出来的文件的源文件

mongodump

-h 导出源

-d 要导出的数据库名称

-o 数据库要导出的位置

mongorestore

-d 使用的数据库名称

-c 恢复一个表

### 数据的导出

Mongodb中的mongoexport工具可以把一个collection导出成JSON格式或CSV格式的文件。可以通过参数指定导出的数据项,也可以根据指定的条件导出数据。

mongoexport

参数说明:

-h:指明数据库宿主机的IP

-u:指明数据库的用户名

-p:指明数据库的密码

-d:指明数据库的名字

-c:指明collection的名字

-f:指明要导出那些列

-o:指明到要导出的文件名

-q:指明导出数据的过滤条件

### 数据的导入

mongoimport

-type 指明要导入的文件格式

-headerline 指明不导入第一行

-file 指明要导入的文件路径

参数说明:

-h:指明数据库宿主机的IP

-u:指明数据库的用户名

-p:指明数据库的密码

-d:指明数据库的名字

-c:指明collection的名字

-f:指明要导入那些列

CSV 格式良好,主流数据库都支持导出为CSV 的格式,所以这种格式非常利于异构数据迁移




### 演示备份数据库

mkdir /bak
cd /bak
[root@redis bak]# mongodump -h 192.168.58.30 --port 27017 -u root -p
connected to: 192.168.58.30:27017
Enter password: 
Thu Jul 17 08:15:42.996 all dbs
Thu Jul 17 08:15:43.006 DATABASE: admin to dump/admin
Thu Jul 17 08:15:43.015 admin.system.indexes to dump/admin/system.indexes.bson
Thu Jul 17 08:15:43.076  2 objects
Thu Jul 17 08:15:43.077 admin.system.users to dump/admin/system.users.bson
Thu Jul 17 08:15:43.077  1 objects
Thu Jul 17 08:15:43.077 Metadata for admin.system.users to dump/admin/system.users.metadata.json
Thu Jul 17 08:15:43.078 DATABASE: guest to dump/guest
Thu Jul 17 08:15:43.082 guest.system.indexes to dump/guest/system.indexes.bson
Thu Jul 17 08:15:43.088  3 objects
Thu Jul 17 08:15:43.088 guest.system.users to dump/guest/system.users.bson
Thu Jul 17 08:15:43.097  1 objects
Thu Jul 17 08:15:43.097 Metadata for guest.system.users to dump/guest/system.users.metadata.json
Thu Jul 17 08:15:43.098 guest.student to dump/guest/student.bson
Thu Jul 17 08:15:43.103  26 objects
Thu Jul 17 08:15:43.103 Metadata for guest.student to dump/guest/student.metadata.json
[root@redis bak]# ll
total 4
drwxr-xr-x 4 root root 4096 Jul 17 08:15 dump
[root@redis bak]# cd dump/
[root@redis dump]# ls
admin  guest
[root@redis dump]#


###恢复数据库

  • 由于刚开始的时候指定了备份目录下面的所有文件,所以会报错

[root@localhost ~]# 
[root@localhost ~]# mongorestore -d admin admin/*
ERROR: too many positional options
Import BSON files into MongoDB.
  • 后来从新换了一个,再次报错

[root@localhost ~]# mongorestore -d admin admin/ 
couldn't connect to [127.0.0.1] couldn't connect to server 127.0.0.1:27017
  • 上面报错是因为我配置文件中写的是本机ip,更换后

[root@localhost ~]# mongorestore -d admin admin/ -h 192.168.58.10     
connected to: 192.168.58.10
Thu Jul 17 09:08:33.873 admin/system.users.bson
Thu Jul 17 09:08:33.873 going into namespace [admin.system.users]
1 objects found
Thu Jul 17 09:08:33.902 Creating index: { key: { _id: 1 }, ns: "admin.system.users", name: "_id_" }
Thu Jul 17 09:08:34.043 Creating index: { key: { user: 1, userSource: 1 }, unique: true, ns: "admin.system.users", name: "user_1_userSource_1" }
[root@localhost ~]#


### 查看是否正确导入

[root@localhost ~]# mongo 192.168.58.10
MongoDB shell version: 2.4.6
connecting to: 192.168.58.10/test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
> show dbsl
Thu Jul 17 09:12:34.806 don't know how to show [dbsl] at src/mongo/shell/utils.js:847
> show dbs;
admin0.203125GB
guest0.203125GB
local0.078125GB
> use guest
switched to db guest
> show collections;
student
system.indexes
system.users
> db.student.find()
{ "_id" : ObjectId("53c769621d184866a15043ec"), "name" : "zhuima" }
{ "_id" : ObjectId("53c769861d184866a15043ed"), "x" : 1 }
{ "_id" : ObjectId("53c769861d184866a15043ee"), "x" : 2 }
{ "_id" : ObjectId("53c769861d184866a15043ef"), "x" : 3 }
{ "_id" : ObjectId("53c769861d184866a15043f0"), "x" : 4 }
{ "_id" : ObjectId("53c769861d184866a15043f1"), "x" : 5 }
{ "_id" : ObjectId("53c769861d184866a15043f2"), "x" : 6 }
{ "_id" : ObjectId("53c769861d184866a15043f3"), "x" : 7 }
{ "_id" : ObjectId("53c769861d184866a15043f4"), "x" : 8 }
{ "_id" : ObjectId("53c769861d184866a15043f5"), "x" : 9 }
{ "_id" : ObjectId("53c769861d184866a15043f6"), "x" : 10 }
{ "_id" : ObjectId("53c769861d184866a15043f7"), "x" : 11 }
{ "_id" : ObjectId("53c769861d184866a15043f8"), "x" : 12 }
{ "_id" : ObjectId("53c769861d184866a15043f9"), "x" : 13 }
{ "_id" : ObjectId("53c769861d184866a15043fa"), "x" : 14 }
{ "_id" : ObjectId("53c769861d184866a15043fb"), "x" : 15 }
{ "_id" : ObjectId("53c769861d184866a15043fc"), "x" : 16 }
{ "_id" : ObjectId("53c769861d184866a15043fd"), "x" : 17 }
{ "_id" : ObjectId("53c769861d184866a15043fe"), "x" : 18 }
{ "_id" : ObjectId("53c769861d184866a15043ff"), "x" : 19 }
Type "it" for more
>



### 用户管理

添加超级用户

use admin

db.addUser('name','password')

添加只读用户

use dbname

db.addUser('name','password',true)

添加普通用户

use dbname

db.addUser('name','password') 其实也不能说是普通用户,这个只是针对于某一个数据库有权限

删除用户

use dbname

db.system.users.remove('name','password')

更换用户密码

use dbname

db.addUser('name','password')

切换用户(必须要先到对对应的数据库,root账户除外)

use dbname

db.auth('name','password')

查找用户

use dbname

db.system.users.find()


### 监控mongodb

1、db.serverStatus()可以查看系统的大部分状态

> db.serverStatus()
{
"host" : "redis.vagrant.internal",
"version" : "2.6.3",
"process" : "mongod",
"pid" : NumberLong(27724),
"uptime" : 4997,
"uptimeMillis" : NumberLong(4997102),
"uptimeEstimate" : 4608,
"localTime" : ISODate("2014-07-21T10:49:35.340Z"),
"asserts" : {
"regular" : 0,
"warning" : 0,
"msg" : 0,
"user" : 4,
"rollovers" : 0
},
"backgroundFlushing" : {
"flushes" : 83,
"total_ms" : 202,
"average_ms" : 2.433734939759036,
"last_ms" : 0,
"last_finished" : ISODate("2014-07-21T10:49:18.431Z")
},
"connections" : {
"current" : 1,
"available" : 51199,
"totalCreated" : NumberLong(2)
},
"cursors" : {
"note" : "deprecated, use server status metrics",
"clientCursors_size" : 0,
"totalOpen" : 0,
"pinned" : 0,
"totalNoTimeout" : 0,
"timedOut" : 0
},
"dur" : {
"commits" : 30,
"journaledMB" : 0,
"writeToDataFilesMB" : 0,
"compression" : 0,
"commitsInWriteLock" : 0,
"earlyCommits" : 0,
"timeMs" : {
"dt" : 3102,
"prepLogBuffer" : 0,
"writeToJournal" : 0,
"writeToDataFiles" : 0,
"remapPrivateView" : 0
}
},
"extra_info" : {
"note" : "fields vary by platform",
"heap_usage_bytes" : 62587072,
"page_faults" : 2
},
"globalLock" : {
"totalTime" : NumberLong("4997106000"),
"lockTime" : NumberLong(466098),
"currentQueue" : {
"total" : 0,
"readers" : 0,
"writers" : 0
},
"activeClients" : {
"total" : 0,
"readers" : 0,
"writers" : 0
}
},
"indexCounters" : {
"accesses" : 48,
"hits" : 48,
"misses" : 0,
"resets" : 0,
"missRatio" : 0
},
"locks" : {
"." : {
"timeLockedMicros" : {
"R" : NumberLong(388976),
"W" : NumberLong(466098)
},
"timeAcquiringMicros" : {
"R" : NumberLong(382921),
"W" : NumberLong(52063)
}
},
"admin" : {
"timeLockedMicros" : {
"r" : NumberLong(239696),
"w" : NumberLong(0)
},
"timeAcquiringMicros" : {
"r" : NumberLong(105140),
"w" : NumberLong(0)
}
},
"local" : {
"timeLockedMicros" : {
"r" : NumberLong(236543),
"w" : NumberLong(842)
},
"timeAcquiringMicros" : {
"r" : NumberLong(73211),
"w" : NumberLong(45)
}
},
"zhuima" : {
"timeLockedMicros" : {
"r" : NumberLong(139309),
"w" : NumberLong(208)
},
"timeAcquiringMicros" : {
"r" : NumberLong(1778),
"w" : NumberLong(3)
}
}
},
"network" : {
"bytesIn" : 12768,
"bytesOut" : 29899,
"numRequests" : 150
},
"opcounters" : {
"insert" : 5,
"query" : 22,
"update" : 9,
"delete" : 4,
"getmore" : 0,
"command" : 141
},
"opcountersRepl" : {
"insert" : 0,
"query" : 0,
"update" : 0,
"delete" : 0,
"getmore" : 0,
"command" : 0
},
"recordStats" : {
"accessesNotInMemory" : 0,
"pageFaultExceptionsThrown" : 0,
"admin" : {
"accessesNotInMemory" : 0,
"pageFaultExceptionsThrown" : 0
},
"local" : {
"accessesNotInMemory" : 0,
"pageFaultExceptionsThrown" : 0
}
},
"writeBacksQueued" : false,
"mem" : {
"bits" : 64,
"resident" : 31,
"virtual" : 2654,
"supported" : true,
"mapped" : 1184,
"mappedWithJournal" : 2368
},
"metrics" : {
"cursor" : {
"timedOut" : NumberLong(0),
"open" : {
"noTimeout" : NumberLong(0),
"pinned" : NumberLong(0),
"total" : NumberLong(0)
}
},
"document" : {
"deleted" : NumberLong(1),
"inserted" : NumberLong(5),
"returned" : NumberLong(81),
"updated" : NumberLong(9)
},
"getLastError" : {
"wtime" : {
"num" : 0,
"totalMillis" : 0
},
"wtimeouts" : NumberLong(0)
},
"operation" : {
"fastmod" : NumberLong(0),
"idhack" : NumberLong(0),
"scanAndOrder" : NumberLong(0)
},
"queryExecutor" : {
"scanned" : NumberLong(9),
"scannedObjects" : NumberLong(9)
},
"record" : {
"moves" : NumberLong(0)
},
"repl" : {
"apply" : {
"batches" : {
"num" : 0,
"totalMillis" : 0
},
"ops" : NumberLong(0)
},
"buffer" : {
"count" : NumberLong(0),
"maxSizeBytes" : 268435456,
"sizeBytes" : NumberLong(0)
},
"network" : {
"bytes" : NumberLong(0),
"getmores" : {
"num" : 0,
"totalMillis" : 0
},
"ops" : NumberLong(0),
"readersCreated" : NumberLong(0)
},
"preload" : {
"docs" : {
"num" : 0,
"totalMillis" : 0
},
"indexes" : {
"num" : 0,
"totalMillis" : 0
}
}
},
"storage" : {
"freelist" : {
"search" : {
"bucketExhausted" : NumberLong(0),
"requests" : NumberLong(5),
"scanned" : NumberLong(8)
}
}
},
"ttl" : {
"deletedDocuments" : NumberLong(0),
"passes" : NumberLong(0)
}
},
"ok" : 1
}
>

2、mongostat 可以动态查看mongodb的各种状态

[root@redis ~]# mongostat -h 192.168.58.30 -uzhuima -pzhuima
connected to: 192.168.58.30
insert  query update delete getmore command flushes mapped  vsize    res faults   locked db idx miss %     qr|qw   ar|aw  netIn netOut  conn       time 
    *0     *0     *0     *0       0     1|0       0  1.16g  2.59g    31m      0 zhuima:0.0%          0       0|0     0|0    62b     3k     1   12:52:12 
    *0     *0     *0     *0       0     1|0       0  1.16g  2.59g    31m      0      .:0.0%          0       0|0     0|0    62b     3k     1   12:52:13 
    *0     *0     *0     *0       0     1|0       0  1.16g  2.59g    31m      0      .:0.1%          0       0|0     0|0    62b     3k     1   12:52:14 
    *0     *0     *0     *0       0     1|0       0  1.16g  2.59g    31m      0 zhuima:0.0%          0       0|0     0|0    62b     3k     1   12:52:15 
    *0     *0     *0     *0       0     1|0       0  1.16g  2.59g    31m      0 zhuima:0.0%          0       0|0     0|0    62b     3k     1   12:52:16 
    *0     *0     *0     *0       0     1|0       0  1.16g  2.59g    31m      0 zhuima:0.0%          0       0|0     0|0    62b     3k     1   12:52:17 
    *0     *0     *0     *0       0     1|0       0  1.16g  2.59g    31m      0 zhuima:0.0%          0       0|0     0|0    62b     3k     1   12:52:18 
^Z
[1]+  Stopped                 mongostat -h 192.168.58.30 -uzhuima -pzhuima
[root@redis ~]#


### 参考文章:

http://blog.csdn.net/shirdrn/article/details/7105539

http://www.cnblogs.com/huangxincheng/archive/2012/03/08/2384571.html