2022-01-26 day78 MongoDB安装部署及增删改查

第2章 MongoDB安装部署

1.目录规划

/opt/mongodb

/opt/mongo_27017/{conf,log,pid}

/data/mongo_27017

2.安装步骤

安装依赖

yum install libcurl openssl -y


#wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.14.tgz

tar zxf mongodb-linux-x86_64-rhel70-4.0.14.tgz -C /opt/



cd /opt/


mv mongodb-linux-x86_64-rhel70-4.0.14 mongodb


#方法1:将可执行命令复制到/usr/local/bin/下

cp /opt/mongodb/bin/* /usr/local/bin/


检查命令补全

#方法2:写入环境变量

echo 'export PATH=/opt/mongodb/bin:$PATH' >> /etc/profile

source /etc/profile

3.创建目录

mkdir -p /opt/mongo_27017/{conf,log,pid}

mkdir -p /data/mongo_27017


4.配置文件

cat > /opt/mongo_27017/conf/mongodb.conf << EOF

systemLog:

  destination: file 

  logAppend: true 

  path: /opt/mongo_27017/log/mongodb.log

storage:

  journal:

    enabled: true

  dbPath: /data/mongo_27017

  directoryPerDB: true

  wiredTiger:

    engineConfig:

      cacheSizeGB: 0.5

      directoryForIndexes: true

    collectionConfig:

      blockCompressor: zlib

    indexConfig:

      prefixCompression: true

processManagement:

  fork: true

  pidFilePath: /opt/mongo_27017/pid/mongod.pid

net:

  port: 27017

  bindIp: 127.0.0.1,10.0.0.51

EOF


5.配置文件注释

systemLog:

  destination: file #Mongodb 日志输出的目的地,指定一个file或者syslog,如果指定file,必须指定

  logAppend: true #当实例重启时,不创建新的日志文件, 在老的日志文件末尾继续添加

  path: /opt/mongo_27017/logs/mongodb.log #日志路径

storage:

  journal: #回滚日志

    enabled: true

  dbPath: /data/mongo_27017 #数据存储目录

  directoryPerDB: true  #默认,false不适用inmemoryengine

  wiredTiger:

    engineConfig:

      cacheSizeGB: 0.5    #将用于所有数据缓存的最大小,也可以改成1表示为1G

      directoryForIndexes: true #默认false索引集合storage.dbPath存储在数据单独子目录

    collectionConfig:

      blockCompressor: zlib

    indexConfig:

      prefixCompression: true

processManagement:      #使用处理系统守护进程的控制处理

  fork: true     #后台运行

  pidFilePath: /opt/mongo_27017/pid/mongod.pid #创建 pid 文件

net:

  port: 27017          #监听端口

  bindIp: 127.0.0.1,10.0.0.51 #绑定ip


6.启动

[root@db-51 ~]# mongod -f /opt/mongo_27017/conf/mongodb.conf

about to fork child process, waiting until server is ready for connections.

forked process: 17694

child process started successfully, parent exiting


7.检查

[root@db-51 ~]# ps -ef|grep mongo

root      17694      1  1 14:55 ?        00:00:00 mongod -f /opt/mongo_27017/conf/mongodb.conf

root      17727  17486  0 14:56 pts/0    00:00:00 grep --color=auto mongo


[root@db-51 ~]# tree /opt/

/opt/

├── mongo_27017

│   ├── conf

│   │   └── mongodb.conf

│   ├── log

│   │   └── mongodb.log

│   └── pid

│      └── mongod.pid

└── mongodb

    └── bin

        ├── bsondump

        ├── install_compass

        ├── mongo

        ├── mongod

        ├── mongodump

        ├── mongoexport

        ├── mongofiles

        ├── mongoimport

        ├── mongoreplay

        ├── mongorestore

        ├── mongos

        ├── mongostat

        └── mongotop


8.登陆

mongo

> show dbs

admin  0.000GB

config  0.000GB

local  0.000GB


2.mongodb优化启动警告

1.数据库没有开启访问控制

** WARNING: Access control is not enabled for the database.

**          Read and write access to data and configuration is unrestricted.

解决方法:

后面章节讲解,暂时不用管

2.root启动不安全

** WARNING: You are running this process as the root user, which is not recommended.

解决方法:

mongod -f /opt/mongo_27017/conf/mongodb.conf --shutdown

查看警告



修复警告

groupadd mongo -g 777

useradd mongo -g 777 -u 777 -M -s /sbin/nologin

id mongo


cat >/usr/lib/systemd/system/mongod.service<

[Unit]

Description=MongoDB Database Server

Documentation=https://docs.mongodb.org/manual

After=network.target

[Service]

User=mongo

Group=mongo

ExecStart=/opt/mongodb/bin/mongod -f /opt/mongo_27017/conf/mongodb.conf

ExecStartPre=/usr/bin/chown -R mongo:mongo /opt/mongo_27017/

ExecStartPre=/usr/bin/chown -R mongo:mongo /data/mongo_27017/

PermissionsStartOnly=true

PIDFile=/opt/mongo_27017/pid/mongod.pid

Type=forking

# file size

LimitFSIZE=infinity

# cpu time

LimitCPU=infinity

# virtual memory size

LimitAS=infinity

# open files

LimitNOFILE=64000

# processes/threads

LimitNPROC=64000

# locked memory

LimitMEMLOCK=infinity

# total threads (user+kernel)

TasksMax=infinity

TasksAccounting=false

# Recommended limits for for mongod as specified in

# http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings

[Install]

WantedBy=multi-user.target

EOF



systemctl daemon-reload

systemctl start mongod.service

ps -ef|grep mongo

mongo


注意:修改配置的时候要先停掉mongo

检查:少了第一条报错

3.关闭大内存页功能

** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.

**        We suggest setting it to 'never'

** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.

**        We suggest setting it to 'never'

解决方法:

echo 'never' > /sys/kernel/mm/transparent_hugepage/enabled

echo 'never' > /sys/kernel/mm/transparent_hugepage/defrag

systemctl restart mongod.service

mongo


4.关闭云监控功能

---

Enable MongoDB's free cloud-based monitoring service, which will then receive and display

metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you

and anyone you share the URL with. MongoDB may use this information to make product

improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()

To permanently disable this reminder, run the following command: db.disableFreeMonitoring()

---

解决方法:

mongo

> db.disableFreeMonitoring()


03 mongo数据库基础知识

1.mongo数据库相关概念

mysql  mongodb

库      库  database

表      集合 collection

字段    键  key

行数据  文档 document

mysql里的数据

user库

user_info表

name   age  job

oldzhang  24 IT

cookzhang  28    cook

xiaozhang  26    IT

mongo里的数据

user 库

user_info 集合

db.user_info.insert

{ name:"oldzhang", age:"24", job:"IT" } 文档

{ name:"cookzhang", age:"28", job:"cook" }      文档

{ name:"xiaozhang", age:"26", job:"IT" }        文档

{ name:"cookya", age:"23", job:"cook" , host:"XZ" }  文档

2.查看数据库命令

#查看所有数据库

> show databases

admin  0.000GB

config  0.000GB

local  0.000GB


> show dbs

admin  0.000GB

config  0.000GB

local  0.000GB


#查看当前所在的库

> db 

test


#切换库

> use zhangya

> db

zhangya


3.默认数据库作用

test:  登陆的时默认的库

admin: 系统预留库,Mongodb的系统管理库

local: 本地预留库,存储关键日志

config: 配置信息库

4.mongo特别的地方

mongo默认登陆的时候是在test库下

mongo不需要提前创建库和表,直接use切换就是创建库,直接插入数据就会创建表

使用use切换到的库,如果没有任何数据,实际上并不会真正创建,是个虚的库,所以show dbs并不会显现



04 mongodb插入命令

插入命令

1.官网地址

https://docs.mongodb.com/manual/crud/

2.语法格式

db.集合名称.操作函数({数据})

3.插入单条数据

use user

db.user_info.insertOne({name: "贺明",age: 26,host: "深圳"})

db.user_info.insertOne({name: "zhang",age: 29,host: "北京"})

db.user_info.insertOne({name: "yazhang",age: 29,host: "上海"})

db.user_info.insertOne({name: "lixiaojie",age: 25,host: "深圳"})


查询插入数据的结果


4.插入多条数据

db.user_info.insertMany([

{name: "laoliu",age: 24,host: "深圳"},

{name: "laozhang",age: 30,host: "深圳"},

{name: "yijie",age: 19,host: "深圳"},

{name: "yijie",age: 19,host: "深圳",job: "IT"}

])


db.user_info.find({})


05 mongodb查询命令

mongo查询语句

1.查询单条

select * from user_info limit 1;

db.user_info.findOne()


2.查询所有

select * from user_info;

db.user_info.find()


3.简单条件查询

select * from user_info where name='yijie';

db.user_info.find({name: "yijie"})


db.user_info.find({age: 29})


4.只返回想要的字段

select name,age from user_info where name='yijie';

db.user_info.find({查询条件},{控制字段显示})

db.user_info.find({name:"yijie"},{name:1,age:1,_id:0})

db.user_info.find(

    {name:"yijie"},

    { 

  name:1,

  age:1,

  _id:0

}

)


5.嵌套查询

#测试数据

db.inventory.insertMany([

  { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },

  { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },

  { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },

  { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },

  { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }

])


查询所在库表


#嵌套查询命令,查询uom为cm的数据

db.inventory.find({"size.uom":"cm"})


db.inventory.find({"size.uom":"cm"},{item:1,status:1,_id:0})


6.运算查询

https://docs.mongodb.com/manual/reference/operator/query-comparison/

select * from inventory where status='A' AND qty < 30;

db.inventory.find( { status: "A", qty: { $lt: 30 } } )

db.inventory.find(

{

status: "A",

qty: { $lt: 30 }

}

)


7.逻辑查询-and

db.inventory.find(

{

status: "A",

"size.h": { $gt: 10 }

}

)


db.inventory.find(

{

status: "A",

"size.h": { $gt: 10 }

},

{

    item: 1,

"size.h": 1,

status: 1,

_id: 0

}

)


8.逻辑查询-or

db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )

db.inventory.find(

{

$or:

[

{ status: "A" },

{ qty: { $lt: 30 } }

]

}

)



9.逻辑查询+或+and+正则表达式

db.inventory.find({

    status: "A",

    $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]

})


跟新数据

先查找数据


db.inventory.updateOne(

    { item: /^P/},

    { 

   $set: { status: "B" } 

  }

)


查询修改后的结果


06 mongodb更新命令

更新数据

db.inventory.find({item: /^p/})


1.更新单条

db.inventory.updateOne(

  { item: /^p/ },

  {

    $set: { status: "P" }

  }

)


2.更新多条

db.inventory.updateMany(

  { item: /^p/ },

  {

    $set: { status: "P" }

  }

)


db.inventory.updateMany(

{

$or:

[

{ status: "A" },

{ qty: { $lt: 30 } }

]

},

{

    $set: { "size.uom":"mm",status: "F"}

}

)


07 mongodb索引

1.查看当前集合的索引

db.inventory.getIndexes()


2.自建ID列

db.user_info.insertOne({id:1,name: "zhang",age: 29,host: "北京"})

db.user_info.insertOne({id:2,name: "yazhang",age: 29,host: "上海"})

db.user_info.insertOne({id:3,name: "yaya",age: 29,host: "深圳"})

db.user_info.find({id:1}).explain()



3.索引种类

COLLSCAN  全表扫描

IXSCAN    索引扫描

4.创建索引

db.user_info.createIndex(

  {

    id: 1

  },

  {

    background: true

  }

)


#查询索引

> db.user_info.getIndexes()

[

{

"v" : 2,

"key" : {

"_id" : 1

},

"name" : "_id_",

"ns" : "zhangya.user_info"

},

{

"v" : 2,

"key" : {

"id" : 1

},

"name" : "id_1",

"ns" : "zhangya.user_info",

"background" : true

}

]

>


#查询计划

> db.user_info.find({id:1}).explain()


08 mongodb删除命令

1.删除索引

db.user_info.getIndexes()


db.user_info.dropIndex("id_1")


查询索引

db.user_info.getIndexes()


2.删除数据

db.user_info.find({id:1})


db.user_info.deleteOne({id:1})


db.inventory.find( {  $or:  [  { status: "F" },  { qty: { $lt: 100 } }  ]  }  )

db.inventory.deleteMany( {  $or:  [  { status: "F" },  { qty: { $lt: 100 } } ] } )


3.删除集合

db.inventory.drop()



db.user_info.drop()

4.删除库

db


db.dropDatabase()


删除库之后,库下面的集合就不存在了


你可能感兴趣的:(2022-01-26 day78 MongoDB安装部署及增删改查)