首页 > 数据库技术 > 详细

每天一篇,学习业内领先的NoSQL数据库=》MongoDB

时间:2018-07-17 00:41:59      阅读:237      评论:0      收藏:0      [点我收藏+]
MongoDB简介:

MongoDB是一款跨平台、面向文档的数据库,可以实现高性能、高可用性,并且能够轻松扩展.

MongoDB也是一个介于非关系数据库和关系数据库之间的产品,是非关系型数据库中功能最丰富,最像关系型数据库的.

运行方式主要基于两个概念:集合与文档

MongoDB的特点:

1、安装简单,提供了面向文档存储功能

2、提供了复制、高可用性和自动分片功能

3、支持丰富的查询表达式,查询指令使用JSON形式的标记

4、支持各种编程语言:Ruby、Pathon、Java、C++、PHP、c#等

下面我在Centos7安装MongoDB并演示相关的各种基础操作

一、安装MongoDB

(1)配置YUM源仓库
[root@localhost ~]#cd /etc/yum.repos.d/
[root@localhost yum.repos.d]#vim mongodb.repo
[mongodb-org]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.6/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc
(2)安装MongoDB
[root@localhost yum.repos.d]#yum list   //测试
[root@localhost ~]#yum  install -y mongodb-org
[root@localhost ~]#vi /etc/mongod.conf
bindIp: 0.0.0.0             #监听地址
port: 27017                 #监听端口
[root@localhost ~]#systemctl start mongod.service
[root@localhost ~]#netstat -anpt | grep 27017
tcp          0          0 0.0.0.0:27017           0.0.0.0:*   
    LISTEN          44010/mongod

[root@localhost ~]#/usr/bin/mongo
>db.version()                //查看版本信息
>show dbs
admin 0.0000GB
local 0.0000GB
> DB.getMongo()
2018-07-16T16:10:27.899+0800 E QUERY    [thread1] TypeError: DB.getMongo is not a function :
@(shell):1:1

二、启动MongoDB多实例

[root@localhost ~]# cp -p /etc/mongod.conf /etc/mongod2.conf
[root@localhost ~]# vim /etc/mongod2.conf
path: /data/mongodb/mongod2.log          //日志位置
dbPath: /data/mongodb/mongo              //存储路径     
port: 27018                              //端口号
[root@localhost ~]# mkdir -p  /data/mongodb/
[root@localhost ~]# cd /data/mongodb/
[root@localhost mongodb]# mkdir mongo
[root@localhost mongodb]# touch mongod2.log
[root@localhost mongodb]# chmod 777 mongod2.log
[root@localhost mongodb]# mongod -f /etc/mongod2.conf
about to fork child process, waiting until server is ready for connections.
forked process: 51823
child process started successfully, parent exiting
[root@localhost mongodb]# mongo --port 27018
MongoDB shell version v3.6.6
connecting to: mongodb://127.0.0.1:27018/
MongoDB server version: 3.6.6
Server has startup warnings: 
2018-07-16T16:21:43.218+0800 I CONTROL  [initandlisten] 
> exit
bye
[root@localhost mongodb]# netstat -antp
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      44010/mongod        
tcp        0      0 0.0.0.0:27018           0.0.0.0:*               LISTEN      51823/mongod        
tcp        0      0 127.0.0.1:49076         127.0.0.1:27018         TIME_WAIT   -                   
tcp        0      0 192.168.200.184:22      192.168.200.1:60220

三、MongoDB基本操作

> use mydb                               //创建并打开mydb数据库
switched to db mydb
> a=db.info.find()                       //起别名
> db.createCollection(‘a‘)              //向mydb数据库添加集合a
{ "ok" : 1 }
> show collections                      //显示数据库中的所有集合
a
> typeof(a.id)                          //查看属性类型
2018-07-16T17:51:21.735+0800 E QUERY    [thread1] ReferenceError: a is not defined :
@(shell):1:1
> db.a.insert({"id":1,"name":"zhangsan","hobby":["game","talk","read"]})
WriteResult({ "nInserted" : 1 })
["game","talk","read"]                   //字符串数组  object(对象)
> db.a.find()                           //显示a集合中的所有文档
{ "_id" : ObjectId("5b4c58ddf7c9ed9a709175e9"), "id" : 1, "name" : "zhangsan", "hobby" : [ "game", "talk", "read" ] }
> db.a.insert({"id":2,"name":"lisi","hobby":["game","talk","read"]})
WriteResult({ "nInserted" : 1 })
> db.a.insert({"id":3,"name":"wangwu","hobby":["game","talk","read"]})
WriteResult({ "nInserted" : 1 })
> db.a.find()
{ "_id" : ObjectId("5b4c58ddf7c9ed9a709175e9"), "id" : 1, "name" : "zhangsan", "hobby" : [ "game", "talk", "read" ] }
{ "_id" : ObjectId("5b4c67c5bacc9efbe3a0d477"), "id" : 2, "name" : "lisi", "hobby" : [ "game", "talk", "read" ] }
{ "_id" : ObjectId("5b4c67ccbacc9efbe3a0d478"), "id" : 3, "name" : "wangwu", "hobby" : [ "game", "talk", "read" ] }
> db.a.findOne({"id":1})                //查找指定记录
{
    "_id" : ObjectId("5b4c58ddf7c9ed9a709175e9"),
    "id" : 1,
    "name" : "zhangsan",
    "hobby" : [
        "game",
        "talk",
        "read"
    ]
}
> db.a.update({"id":2},{$set:{"name":"xiaoqi"}})    //更改属性
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.a.find()
{ "_id" : ObjectId("5b4c58ddf7c9ed9a709175e9"), "id" : 1, "name" : "zhangsan", "hobby" : [ "game", "talk", "read" ] }
{ "_id" : ObjectId("5b4c67c5bacc9efbe3a0d477"), "id" : 2, "name" : "xiaoqi", "hobby" : [ "game", "talk", "read" ] }
{ "_id" : ObjectId("5b4c67ccbacc9efbe3a0d478"), "id" : 3, "name" : "wangwu", "hobby" : [ "game", "talk", "read" ] }
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
mydb    0.000GB
> use mydb
switched to db mydb
> db.a.drop()                            //删除集合
true
> show collections
> db.dropDatabase()                      //删除数据库
{ "dropped" : "mydb", "ok" : 1 }
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

四、MongoDB日常维护

参数说明:

-d:指明数据库的名字

-c:指明集合的名字

-f:指明要导出哪些列

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

-q:指明导出数据的过滤条件
(1)导入导出

使用mongoexport和mongoimport命令来导入导出MongoDB的数据

> use school
switched to db school
> db.createCollection(‘info‘)
{ "ok" : 1 }
> for(var i=1;i<=100;i++)db.info.insert({"id":i,"name":"jack"+i})
WriteResult({ "nInserted" : 1 })
> db.info.find()
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572da"), "id" : 1, "name" : "jack1" }
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572db"), "id" : 2, "name" : "jack2" }
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572dc"), "id" : 3, "name" : "jack3" }
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572dd"), "id" : 4, "name" : "jack4" }
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572de"), "id" : 5, "name" : "jack5" }
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572df"), "id" : 6, "name" : "jack6" 
> db.info.count()                      //显示行数
100
[root@localhost ~]# mongoexport -d school -c info -o /opt/school.json  //这里注意导出的文件格式为*.json
c2018-07-16T22:13:22.668+0800   connected to: localhost
2018-07-16T22:13:22.675+0800    exported 100 records
[root@localhost ~]# cd /opt
[root@localhost opt]# ls
rh  school.json
[root@localhost opt]# vim school.json 
[root@localhost opt]# mongoimport -d school -c test --file school.json
2018-07-16T22:15:22.523+0800    connected to: localhost
2018-07-16T22:15:22.700+0800    imported 100 documents
[root@localhost opt]# mongo
> use school
switched to db school
> show tables
info
test                          //导入文件test,是刚才导出的内容
> db.test.find()
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572da"), "id" : 1, "name" : "jack1" }
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572db"), "id" : 2, "name" : "jack2" }
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572dc"), "id" : 3, "name" : "jack3" }
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572dd"), "id" : 4, "name" : "jack4" }
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572de"), "id" : 5, "name" : "jack5" }
{ "_id" : ObjectId("5b4ca7864f78ab07f2b572df"), "id" : 6, "name" : "jack6"
[root@localhost opt]# mongoexport -d school -c info -q ‘{               "id":{"$eq":10}}‘ -o /opt/top10.json    //筛选需要导出的行数,-q后面有空格
2018-07-16T22:20:20.610+0800    connected to: localhost
2018-07-16T22:20:20.636+0800    exported 1 record
[root@localhost opt]# cd /opt/
[root@localhost opt]# ls
rh  school.json  top10.json
[root@localhost opt]# vim top10.json 

{"_id":{"$oid":"5b4ca7864f78ab07f2b572e3"},"id":10.0,"name":"jack10"}
(2)备份与恢复

使用Mongodump命令来备份MongoDB数据

-h:MongoDB所在服务器地址

-d:需要备份的数据库实例

-o:备份数据存放的位置,该目录需提前创建
[root@localhost opt]# mkdir /backup
[root@localhost opt]# mongodump -d school -o /backup/       //备份
2018-07-16T22:43:29.828+0800    writing school.info to 
2018-07-16T22:43:29.830+0800    writing school.test to 
2018-07-16T22:43:29.836+0800    done dumping school.info (100 documents)
2018-07-16T22:43:29.838+0800    done dumping school.test (100 documents)
[root@localhost opt]# cd /backup/
[root@localhost backup]# ls
school
[root@localhost backup]# cd school/
[root@localhost school]# ls
info.bson  info.metadata.json  ==test.bson==  test.metadata.json
[root@localhost school]# mongorestore -d abc --dir=/backup/school/  //恢复  备注:这里的数据库abc会自动创建,所以可以不存在
2018-07-16T22:46:02.801+0800    the --db and --collection args should only be used when restoring from a BSON file. Other uses are deprecated and will not exist in the future; use --nsInclude instead
(3)复制数据库
> show dbs
abc     0.000GB
admin   0.000GB
config  0.000GB
local   0.000GB
school  0.000GB
> show dbs
abc     0.000GB
admin   0.000GB
config  0.000GB
local   0.000GB
school  0.000GB
> db.copyDatabase("abc","abc1")               //复制数据库        
{ "ok" : 1 }
> show dbs
abc     0.000GB
abc1    0.000GB
admin   0.000GB
config  0.000GB
local   0.000GB
school  0.000GB
(4)创建管理用户
> use admin
> db.createUser({"user":"root","pwd":"123","roles":["root"]})
> db.auth("root","123")
(5)进程管理
> db.currentOp()          //查看进程
    "active" : true,
            "currentOpTime" : "2018-07-16T23:28:31.188+0800",
            "opid" : 19385,
            "secs_running" : NumberLong(0),
    > db.killOp(19385)
{ "info" : "attempting to kill op", "ok" : 1 }

每天一篇,学习业内领先的NoSQL数据库=》MongoDB

原文:http://blog.51cto.com/13687553/2145096

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!