code block怎样导入整个文件夹_MySQL数据导入到MongoDb教程

1、安装与配置MySQL

  • 首先下载MySQL免安装包,版本是mysql-5.6.24。网址是//dev.mysql.com/downloads/mysql/
  • 解压MySQL软件包,得到如下目录:

f018d8e526ac868e1f9856bfef4ebd53.png
  • 配置MySQL的系统环境变量:
    • 打开 Windows 环境变量设置, 新建变量名MYSQL_HOME,变量值为MySQL安装目录路径, 这里为D:DownloadFilesmysql
    • 在环境变量的Path变量中添加;%MYSQL_HOME%bin;
  • MySQL-5.6默认的配置文件是D:DownloadFilesmysqlmy-default.ini如果想要换成你自己的配置文件,待会安装MySQL服务的时候加上参数--defaults-file="my.ini"
  • 修改配置文件,这里使用默认的配置文件,所以修改my-default.ini如下:
# For advice on how to change settings please see
# //dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html
# *** DO NOT EDIT THIS FILE. It's a template which will be copied to the
# *** default location during install, and will be replaced if you
# *** upgrade to a newer version of MySQL.

[mysqld]

# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M

# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin

# These are commonly set, remove the # and set as required.
 basedir = D:DownloadFilesmysql
 datadir = D:DownloadFilesmysqldata
# port = .....
# server_id = .....


# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M 

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
  • 以管理员的身份运行CMD,启动命令行窗口,然后安装MySQL服务: mysqld -installmysqld -install MySQL --defaults-file="my.ini" 当提示"Service successfully installed."表示安装成功。注意:如果使用自己的配置文件参数是--defaults-file而不是--default-file哦!否则会在启动MySQL服务的时候报错:C:WINDOWSsystem32>net start mySQL The MySQL service is starting... The MySQL service could not be started. A system error has occurred. System error 1067 has occurred. The process terminated unexpectedly . 出现这个错误的时候可以去查看MySQL的错误日志,文件位于D:DownloadFilesmysqldata中,文件一般是以err为后缀名的文件,里面可以看到启动服务时出错的原因,这样就可以解决了。
  • 启动MySQL服务,如果没有启动而贸然连接的话会报错:ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061),命令如下: net start mysql 关闭服务:net stop mysql。如果出现错误:
发生系统错误 2。

系统找不到指定的文件。

那么是因为注册表的问题,只需要去修改HKEY_LOCAL_MACHINE-SYSTEM-CurrentControlSet-services-mysql-ImagePath的值,修改为当前你的MySQL的解压缩的路径,当前是D:DownloadFilesmysqldata

  • 登录MySQL 执行mysql -uroot -p,之后会出现Enter password:的时候不需要输入密码,因为是第一次登录,所以千万不要输入密码,否则之后就会一直错误一直拒绝登录。登录成功显示:
D:DownloadFilesmysql>mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 1
Server version: 5.6.24 MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
  • 为root用户设置密码: set password=password('你的密码');,成功的话会提示: Query OK, 0 rows affected (0.00 sec)
  • 重新刷新权限: flush privileges;,成功的话也会提示一样的语句。

2、使用MySQL-Front操作MySQL

  • 先连接上MySQL,打开MySQL-Front软件,按快捷键F12打开登录信息,新建一个连接:

28ac49a603cd09cc0dd52e178296398a.png

填上刚才root用户设置的密码,以及主机名(localhost),然后连接即可,连接上的界面如下:

236680ceaad37b317c59e5ebf0cc793d.png
  • 新建一个数据库,如图操作:

9aca9065e4602699376adbdb9d7a5fe3.png

然后选择正确的字符集,点击确定就ok了。

cd713dcff529da215fe645f1f53f1818.png
  • 接着将已存在的.sql的数据库导入到我们新建的数据库中,导入步骤如下:

6a320bd95d096320cd4e4c76e4c1e07f.png

成功导入之后可以看到结果:

64f9494eb390a5f2ee639b356c137389.png

3、启动与配置MongoDB

  • 在windows下载MongoDb,之后安装成功,并将MongoDb的安装目录的Bin文件夹配置到环境变量中,如下图:

bf4be76dc20aa30d29399983839da369.png
  • 选择一个MongoDb的数据和日志存储目录,比如E:MongoDb,然后在该文件夹下新建一个配置文件:mongodb.config(名字随便取)。文件简单配置如下:
dbpath=E:MongoDbdata
logpath=E:MongoDblogmongoDbLog.log
#这个第一次启动的时候不要加这个选项,等到创建管理员用户之后再加进去重新启动数据库
auth=true
  • 启动MongoDb 命令如下:mongod --config E:MongoDbmongodb.config --storageEngine mmapv1 启动成功日志:

ee30f88629dbd70b4996852076d9a426.png
注意:后面的存储引擎的配置是因为刚开始采用默认的存储引擎: wiredTiger(二者有什么区别暂时没有去深究)的时候,在MongoDb中添加了任何数据在MongoVUE软件中一直看不到,后来网上搜索了一下才发现还有这种坑。然后就指定了mmapv1这种存储引擎。另外如果刚开始使用默认的,后来要切换到新的存储引擎的话,存储数据的文件夹就不能和以前的文件夹一样,需要新建一个。
  • 连接MongoDb 接着我们另外开一个CMD窗口,连接MongoDb服务器:
C:Windowssystem32>mongo
MongoDB shell version: 3.2.4
connecting to: test
>

因为此时我们开启了服务器的鉴权配置,但是此时我们没有任何用户密码,并且是没有密码登录进去的,所以日志就会提示红色框中的两行。 这个时候如果你查看数据库信息是会被拒绝的,所以需要注释掉配置文件中的auth=true这行。

> show dbs
2016-04-20T20:54:33.201+0800 E QUERY    [thread1] Error: listDatabases failed:{
        "ok" : 0,
        "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
        "code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:23:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:53:1
shellHelper.show@src/mongo/shell/utils.js:700:19
shellHelper@src/mongo/shell/utils.js:594:15
@(shellhelp2):1:1
  • 新建一个数据库并添加用户 MongoDb自从2.6版本之后用户管理以及安全性有了很大的提高,能够做到非常细微的安全管理。其中添加用户从命令addUser变成了createUser,并且参数也得到扩展:(也就是多了一个role的参数) db.createUser({user:'**',pwd:'***',roles:[***,**]})
  • 新建一个管理员账户
> use admin
switched to db admin
> db.createUser(
{
  user: "admin",
  pwd: "123456",
  roles:
  [
    {
      role: "userAdminAnyDatabase",
      db: "admin"
    }
  ]
}
)
Successfully added user: {
     "user" : "admin",
     "roles" : [
             {
                     "role" : "userAdminAnyDatabase",
                     "db" : "admin"
             }
     ]
}
>
  • 新建forum数据库并添加用户 重启MongoDB,键入下面命令,使用管理员权限登录如下:
> use admin
switched to db admin
> db.auth("admin", "123456")
1
> db.runCommand(
...     {
...         usersInfo:"admin",
...         showPrivileges:true
...     }
... )
{
 "users" : [
         {
                 "_id" : "admin.admin",
                 "user" : "admin",
                 "db" : "admin",
                 "roles" : [
                         {
                                 "role" : "userAdminAnyDatabase",
                                 "db" : "admin"
                         }
                 ],
                 "inheritedRoles" : [
                         {
                                 "role" : "userAdminAnyDatabase",
                                 "db" : "admin"
                         }
                 ],
                 "inheritedPrivileges" : [
                         {
                                 "resource" : {
                                         "db" : "",
                                         "collection" : ""
                                 },
                                 "actions" : [
                                         "changeCustomData",
                                         "changePassword",
                                         "createRole",
                                         "createUser",
                                         "dropRole",
                                         "dropUser",
                                         "grantRole",
                                         "revokeRole",
                                         "viewRole",
                                         "viewUser"
                                 ]
                         },
                         {
                                 "resource" : {
                                         "cluster" : true
                                 },
                                 "actions" : [
                                         "authSchemaUpgrade",
                                         "invalidateUserCache",
                                         "listDatabases"
                                 ]
                         },
                         {
                                 "resource" : {
                                         "db" : "",
                                         "collection" : "system.users"
                                 },
                                 "actions" : [
                                         "collStats",
                                         "dbHash",
                                         "dbStats",
                                         "find",
                                         "killCursors",
                                         "listCollections",
                                         "listIndexes",
                                         "planCacheRead"
                                 ]
                         },
                         {
                                 "resource" : {
                                         "db" : "admin",
                                         "collection" : "system.users"
                                 },
                                 "actions" : [
                                         "collStats",
                                         "createIndex",
                                         "dbHash",
                                         "dbStats",
                                         "dropIndex",
                                         "find",
                                         "killCursors",
                                         "listCollections",
                                         "listIndexes",
                                         "planCacheRead"
                                 ]
                         },
                         {
                                 "resource" : {
                                         "db" : "admin",
                                         "collection" : "system.roles"
                                 },
                                 "actions" : [
                                         "collStats",
                                         "createIndex",
                                         "dbHash",
                                         "dbStats",
                                         "dropIndex",
                                         "find",
                                         "killCursors",
                                         "listCollections",
                                         "listIndexes",
                                         "planCacheRead"
                                 ]
                         },
                         {
                                 "resource" : {
                                         "db" : "admin",
                                         "collection" : "system.version"
                                 },
                                 "actions" : [
                                         "collStats",
                                         "dbHash",
                                         "dbStats",
                                         "find",
                                         "killCursors",
                                         "listCollections",
                                         "listIndexes",
                                         "planCacheRead"
                                 ]
                         },
                         {
                                 "resource" : {
                                         "db" : "admin",
                                         "collection" : "system.new_users"
                                 },
                                 "actions" : [
                                         "collStats",
                                         "dbHash",
                                         "dbStats",
                                         "find",
                                         "killCursors",
                                         "listCollections",
                                         "listIndexes",
                                         "planCacheRead"
                                 ]
                         },
                         {
                                 "resource" : {
                                         "db" : "admin",
                                         "collection" : "system.backup_users"
                                 },
                                 "actions" : [
                                         "collStats",
                                         "dbHash",
                                         "dbStats",
                                         "find",
                                         "killCursors",
                                         "listCollections",
                                         "listIndexes",
                                         "planCacheRead"
                                 ]
                         }
                 ]
         }
 ],
 "ok" : 1
}
>


其次新建一个我们的数据库:use forum,当你敲入这个命令的时候,如果服务器中没有这个数据库便会新建一个数据库。

接着我们创建一个用户:

> db.createUser( { "user" : "forum",
                 "pwd": "123456",
                 "customData" : { employeeId: 12345 },
                 "roles" : [ { role: "dbOwner", db: "forum" }]
                 },
               { w: "majority" , wtimeout: 5000 } )

新建成功的提示:

Successfully added user: {
        "user" : "forum",
        "customData" : {
                "employeeId" : 12345
        },
        "roles" : [
                {
                        "role" : "dbOwner",
                        "db" : "forum"
                }
        ]
}
>

查看系统当前用户:

> show users
{
        "_id" : "forum.forum",
        "user" : "forum",
        "db" : "forum",
        "customData" : {
                "employeeId" : 12345
        },
        "roles" : [
                {
                        "role" : "dbOwner",
                        "db" : "forum"
                }
        ]
}
这里有一个小问题:如果你是在数据库test下创建一个可以操作forum数据库的用户,那么第三个字段 db显示的是你当前所在的数据库,我经过试验发现那样的话你在forum数据库认证该用户会出现认证失败的情况,这个问题有待解释!!

备注:

Built-In Roles(内置角色):

1. 数据库用户角色:read、readWrite;
2. 数据库管理角色:dbAdmin、dbOwner、userAdmin;
3. 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
4. 备份恢复角色:backup、restore;
5. 所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
6. 超级用户角色:root  
// 这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase)
7. 内部角色:__system
  • 重新开启鉴权启动数据库 这次重启数据库之后连接的时候就可以采用用户名和密码的方式来连接:

mongo -u forum -p 123456

成功之后可以查看admin这个数据库的集合:

> use admin
switched to db admin
> show collections
system.indexes
system.users
system.version
  • 打开MongoVUE连接MongoDb 下载的MongoVUE的软件有点老旧,新版本在官网上一直访问不了,不知道为啥?下载地址: //download.csdn.net/download/show_594/7484123 打开软件之后新建一个连接:

b9e16f6e2c6ff573d50331e84ed7e177.png

之后点击红色的框框测试连接,如果这个时候报错误:

e86856e9fcb9a16e1b47bc1465b237dd.png
Connection was refused
Unable to connect to server localhost:27017: Invalid credential for database 'forum'..
Type: MongoDB.Driver.MongoConnectionException
Stack:    在 MongoDB.Driver.Internal.DirectMongoServerProxy.Connect(TimeSpan timeout, ReadPreference readPreference)
   在 MongoDB.Driver.MongoServer.Connect(TimeSpan timeout)
   在 MongoDB.Driver.MongoServer.Connect()
   在 MangoUI.MMongo.Open(Boolean mustWrite)
   在 MangoUI.MMongo.Open()
   在 MangoUI.MConnection.get_IsValid()
   在 MangoUI.WinConnect.btnTest_Click(Object sender, EventArgs e)


Invalid credential for database 'forum'.
Type: MongoDB.Driver.MongoAuthenticationException
Stack:    在 MongoDB.Driver.Communication.Security.MongoCRAuthenticationProtocol.Authenticate(MongoConnection connection, MongoCredential credential)
   在 MongoDB.Driver.Communication.Security.Authenticator.Authenticate(MongoCredential credential)
   在 MongoDB.Driver.Communication.Security.Authenticator.Authenticate()
   在 MongoDB.Driver.Internal.MongoConnection.Open()
   在 MongoDB.Driver.Internal.MongoConnection.GetNetworkStream()
   在 MongoDB.Driver.Internal.MongoConnection.SendMessage(BsonBuffer buffer, Int32 requestId)
   在 MongoDB.Driver.Internal.MongoConnection.SendMessage(MongoRequestMessage message)
   在 MongoDB.Driver.Operations.CommandOperation`1.Execute(MongoConnection connection)
   在 MongoDB.Driver.MongoServerInstance.RunCommandAs[TCommandResult](MongoConnection connection, String databaseName, IMongoCommand command)
   在 MongoDB.Driver.MongoServerInstance.Ping(MongoConnection connection)
   在 MongoDB.Driver.MongoServerInstance.Connect()
   在 MongoDB.Driver.Internal.DirectMongoServerProxy.Connect(TimeSpan timeout, ReadPreference readPreference)


Command 'authenticate' failed: auth failed (response: { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18 })
Type: MongoDB.Driver.MongoCommandException
Stack:    在 MongoDB.Driver.Operations.CommandOperation`1.Execute(MongoConnection connection)
   在 MongoDB.Driver.Communication.Security.MongoCRAuthenticationProtocol.RunCommand(MongoConnection connection, String databaseName, IMongoCommand command)
   在 MongoDB.Driver.Communication.Security.MongoCRAuthenticationProtocol.Authenticate(MongoConnection connection, MongoCredential credential)
Inputs:: 
Command:  authenticate
Ok:       False
ErrorMsg: auth failed
Request:  { "authenticate" : 1, "user" : "forum", "nonce" : "a7926dad539b682f", "key" : "0a5b321ba5814aa59f3b428aa8a1845d" }
Response: { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18 }

并且查看日志有:

[conn9]  authenticate db: forum { authenticate: 1, user: "forum", nonce: "xxx", key: "xxx" }
2016-04-20T22:08:20.965+0800 I ACCESS   [conn9] Failed to authenticate forum@forum with mechanism MONGODB-CR: AuthenticationFailed: MONGODB-CR credentials missing in the user document

那么解决方法是:

注意:执行下面的命令的时候因为用户权限不够,所以需要暂时关掉鉴权再重启服务器执行这些命令。
C:Windowssystem32>mongo
MongoDB shell version: 3.2.4
connecting to: test
> use admin
switched to db admin
>
>
> db.system.users.remove({})
WriteResult({ "nRemoved" : 2 })
> db.system.version.remove({})
WriteResult({ "nRemoved" : 1 })
> db.system.version.insert({ "_id" : "authSchema", "currentVersion" : 3 })
WriteResult({ "nInserted" : 1 })

之后就可以连接成功:

d0f61db6bfae6105316f928c4b24836a.png

原因:

MongoDB 3 authentication mechanism has been changed from : MongoDB Challenge and Response (MONGODB-CR) to challenge and response mechanism (SCRAM-SHA-1). You have to delete your created user then change admin.system.version.authSchema to 3 instead of 5. 参考:https://docs.mongodb.org/manual/core/authentication/。

备注:Unable to connect to server localhost:27017: 未将对象引用设置到对象的实例。 因为我们新创建的而且很多数据库都是新的什么也没有,所以一般就是直接置空。如果你确定有相应的用户名密码数据库再填上。
  • 导入MySQL数据库 下图是MongoDb数据库,可以看到我们创建的forum数据库以及新建的一条记录:

ca6f4b1e9121d63496a5e1e4c919d0e1.png

接下去我们将导入MySQL数据库,如下图所示操作:

75c80f6549311e4ed9c2b1a5d452e984.png

fd648d7482e52317268d054315311e68.png

接着选择我们需要导入的数据库以及集合,这里以member为例子导入:

61c45fa643ce568ce36e0547a39162da.png

导入成功之后我们可以看到forum数据库多了mvforummember这个集合。

6909381c7ccc249081c797ef8bb0269c.png
  • 导出MongoDb的数据 命令格式如下: mongoexport -d dataname -c collection -o file 所以我们在命令行可以输入:
E:MongoDb>mongoexport -d forum -c mvnforummember -o member.json --username forum --password 123456
2016-04-20T22:47:50.050+0800    connected to: localhost
2016-04-20T22:47:50.558+0800    exported 4075 records
  • 如果用的是mondodump则是dump出不一样的数据:
E:MongoDb>mongodump -h localhost -d forum -o ./dump/ --username forum --password 123456
2016-04-20T22:44:38.716+0800    writing forum.system.indexes to
2016-04-20T22:44:38.720+0800    done dumping forum.system.indexes (2 documents)
2016-04-20T22:44:38.721+0800    writing forum.forum to
2016-04-20T22:44:38.722+0800    writing forum.mvnforummember to
2016-04-20T22:44:38.723+0800    done dumping forum.forum (1 document)
2016-04-20T22:44:38.790+0800    done dumping forum.mvnforummember (4075 documents)

因为我们要将这些数据导入到Linux系统中的MongoDb服务器,所以需要的json数据。

  • 导入Mongo数据到Linux系统中的MongoDb服务器中 命令是: mongoimport -d forum -c member -f member.json

如果是刚才使用mongodump导出的数据那么需要使用配套的mongostore命令来恢复数据。 mongorestore -d forum -c mvnforummember --dir=./dump/forum/mvnforummember.bson

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值