search
HomeDatabaseMysql Tutorialmonogdb之数据备份恢复与数据的导入导出

### 备份方式和恢复方式 备份全部数据库 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


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.