参考链接:
MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。在高负载的情况下,添加更多的节点,可以保证服务器性能。MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。
主要特点 MongoDB 是一个面向文档存储的数据库,操作起来比较简单和容易。 你可以在MongoDB记录中设置任何属性的索引 (如:FirstName="Sameer",Address="8 Gandhi Road")来实现更快的排序。 你可以通过本地或者网络创建数据镜像,这使得MongoDB有更强的扩展性。 如果负载的增加(需要更多的存储空间和更强的处理能力) ,它可以分布在计算机网络中的其他节点上这就是所谓的分片。 Mongo支持丰富的查询表达式。查询指令使用JSON形式的标记,可轻易查询文档中内嵌的对象及数组。 MongoDb 使用update()命令可以实现替换完成的文档(数据)或者一些指定的数据字段 。 Mongodb中的Map/reduce主要是用来对数据进行批量处理和聚合操作。 Map和Reduce。Map函数调用emit(key,value)遍历集合中所有的记录,将key与value传给Reduce函数进行处理。 Map函数和Reduce函数是使用Javascript编写的,并可以通过db.runCommand或mapreduce命令来执行MapReduce操作。 GridFS是MongoDB中的一个内置功能,可以用于存放大量小文件。 MongoDB允许在服务端执行脚本,可以用Javascript编写某个函数,直接在服务端执行,也可以把函数的定义存储在服务端,下次直接调用即可。 MongoDB支持各种编程语言:RUBY,PYTHON,JAVA,C++,PHP,C#等多种语言。 MongoDB安装简单。
#1.安装依赖包 sudo yum install libcurl openssl #centos redhat sudo apt-get install libcurl4 openssl ubantu 18.04 LTS#2.下载源码包参考链接:MongoDB 源码下载地址:https://www.mongodb.com/download-center#community#3.下载二进制包 wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.2.17.tgz # 下载#4.解压到具体目录 mv mongodb-linux-x86_64-rhel70-4.2.17.tgz /usr/local/mongodb4 # 将解压包拷贝到指定目录#5.配置环境变量 echo "export PATH=$PATH:/usr/local/mongodb4/bin" >>/etc/profile source /etc/profile#6.创建相关目录 数据存储目录:/var/lib/mongodb 日志文件目录:/var/log/mongodb sudo mkdir -p /var/lib/mongo sudo mkdir -p /var/log/mongodb sudo chown `whoami` /var/lib/mongo # 设置权限 sudo chown `whoami` /var/log/mongodb # 设置权限#7.启动mongodb服务 默认端口为:10503mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --fork [root@shell ~23:18:56]# mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --fork about to fork child process, waiting until server is ready for connections. forked process: 10503 child process started successfully, parent exiting[root@shell ~23:19:10]# netstat -lntup |grep mongo tcp 0 0 127.0.0.1:27017 0.0.0.0:* LISTEN 10503/mongod #参数说明: -h:指明数据库宿主机的IP -u:指明数据库的用户名 -p:指明数据库的密码 -d:指明数据库的名字 -c:指明collection的名字 -o:指明到要导出的文件名 -q:指明导出的过滤条件 -j,--numParallclCollections= number of collectiions to dum in parallel#8.停止mongodb 方法一: mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --shutdown方法二: > use admin switched to db admin > db.shutdownServer()#9.查看日志文件是否启动成功 [root@shell ~23:19:25]# tail -10f /var/log/mongodb/mongod.log 2021-10-16T23:19:10.399+0800 I STORAGE [LogicalSessionCacheRefresh] createCollection: config.system.sessions with provided UUID: 520fda48-31c3-45f9-8394-048c2b664b49 and options: { uuid: UUID("520fda48-31c3-45f9-8394-048c2b664b49") } 2021-10-16T23:19:10.400+0800 I NETWORK [listener] Listening on /tmp/mongodb-27017.sock 2021-10-16T23:19:10.401+0800 I NETWORK [listener] Listening on 127.0.0.1 2021-10-16T23:19:10.401+0800 I NETWORK [listener] waiting for connections on port 27017 2021-10-16T23:19:10.414+0800 I INDEX [LogicalSessionCacheRefresh] index build: done building index _id_ on ns config.system.sessions 2021-10-16T23:19:10.424+0800 I INDEX [LogicalSessionCacheRefresh] index build: starting on config.system.sessions properties: { v: 2, key: { lastUse: 1 }, name: "lsidTTLIndex", ns: "config.system.sessions", expireAfterSeconds: 1800 } using method: Hybrid 2021-10-16T23:19:10.425+0800 I INDEX [LogicalSessionCacheRefresh] build may temporarily use up to 200 megabytes of RAM 2021-10-16T23:19:10.425+0800 I INDEX [LogicalSessionCacheRefresh] index build: collection scan done. scanned 0 total records in 0 seconds 2021-10-16T23:19:10.426+0800 I INDEX [LogicalSessionCacheRefresh] index build: inserted 0 keys from external sorter into index in 0 seconds 2021-10-16T23:19:10.427+0800 I INDEX [LogicalSessionCacheRefresh] index build: done building index lsidTTLIndex on ns config.system.sessions
#1.进入安装路径的bin 目录下cd /usr/local/mongodb4/bin输入./mongo +回车[root@shell /usr/local/mongodb4/bin23:22:58]# mongo MongoDB shell version v4.2.17 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("9370b83b-492c-4f62-b54d-e7cdadce6f06") } MongoDB server version: 4.2.17 Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, seehttps://docs.mongodb.com/ Questions? Try the MongoDB Developer Community Forumshttps://community.mongodb.com Server has startup warnings: 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended. 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** WARNING: This server is bound to localhost. 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** Remote systems will be unable to connect to this server. 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** Start the server with --bind_ip <address> to specify which IP 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** addresses it should serve responses from, or with --bind_ip_all to 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** bind to all interfaces. If this behavior is desired, start the 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** server with --bind_ip 127.0.0.1 to disable this warning. 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never' 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never' 2021-10-16T23:19:10.328+0800 I CONTROL [initandlisten] --- 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()#2.测试数据 > 1 +1 2 > 1+4 5 > 100*100 10000#插入数据 > db.runoob.insert({x:10}) WriteResult({ "nInserted" : 1 })#查看数据 > db.runoob.find() { "_id" : ObjectId("616aee731b401b9fc72193da"), "x" : 10 }
#1.全库备份 mkdir /mongodb/backup mongodump -uroot -proot123 --port 27017 --authenticationDatabase admin -o /mongodb/backup #2.备份world库 mongodum -uroot -proot123 --port 27017 --authenticationDatabase admin -d world -o /mongodb/backup #3.备份oldboy库下的Log集合 mongodum -uroot -proot123 --port 27017 --authenticationDatabase admin -d oldboy -c log -o /mongodb/backup #4.压缩备份 mongodum -uroot -proot123 --port 27017 --authenticationDatabase admin -o /mongodb/backup/ --gzip #5.恢复test库 mongorestore -uroot -proot123 --port 27017 --authenticationDatabase admin -d test1 /mongodb/backup/test --gzip
一.Mongod基础运维部分
1.安装MongoDB
#软件下载
https://www.mongodb.com/try/download/community
#2.上传解压mongod软件
mkdir -p /mongodb && cd /mongodb
rz mongodb-linux-x86_64-rhel70-4.2.8.tgz
tar xf mongodb-linux-x86_64-rhel70-4.2.8.tgz
mv mongodb-linux-x86_64-rhel70-4.2.8.tgz /usr/local/mongodb
#3.添加环境变量
vim /etc/profile
export PATH=/usr/local/mongodb/bin:$PATH
source /etc/profile
#4.关闭THP
root用户下
在vim /etc/rc.local最后添加如下代码
if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
echo never > /sys/kernel/mm/transparent_hugepage/enabled
fi
if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
echo never > /sys/kernel/mm/transparent_hugepage/defrag
fi
查看:
[root@lss mongodb]# cat /sys/kernel/mm/transparent_hugepage/enabled
[always] madvise never
[root@lss mongodb]# cat /sys/kernel/mm/transparent_hugepage/defrag
[always] madvise never
其他系统关闭参照官方文档:
https://docs.mongodb.com/manual/tutorial/transparent-huge-pages/
为什么要关闭?
Transparent Huge Pages (THP) is a Linux memory management system
that reduces the overhead of Translation Lookaside Buffer (TLB)
lookups on machines with large amounts of memory by using larger memory pages.
However, database workloads often perform poorly with THP,
because they tend to have sparse rather than contiguous memory access patterns.
You should disable THP on Linux machines to ensure best performance with
MongoDB.
透明巨型页面(THP)是一个Linux内存管理系统,这减少了转换查找缓冲区(TLB)的开销,通过使用更大的内存页查找具有大量内存的机器。然而,使用THP时,数据库工作负载通常表现不佳,因为它们往往具有稀疏而非连续的内存访问模式。您应该在Linux机器上禁用THP,以确保最佳性能MongoDB。
2.环境准备
(1)创建所需用户和组
useradd mongod
passwd mongod
输入mongod(密码)
(2)创建mongodb所需目录结构
mkdir -p /mongodb/conf
mkdir -p /mongodb/log
mkdir -p /mongodb/data
(3) 修改权限
chown -R mongod:mongod /mongodb
(4) 切换用户并设置环境变量
su - mongod
vi .bash_profile
export PATH=/usr/local/mongodb/bin:$PATH
source .bash_profile
3.启动数据库并初始化数据
#1.方式一:直接命令启动
su - mongod
mongod --dbpath=/mongodb/data --logpath=/mongodb/log/mongodb.log --port=27017 --logappend --fork
[mongod@lss conf]$ mongo
MongoDB shell version v4.2.8
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("f52da758-bd97-4c95-a54c-d6276d8c7dc1") }
MongoDB server version: 4.2.8
show databases;
use admin;
show tables;
#2.方式二:用配置文档启动
1.常规配置文档
vim /mongodb/conf/mongodb.conf
logpath=/mongodb/log/mongodb.log
dbpath=/mongodb/data
port=27017
logappend=true
fork=true
# 关闭mongodb
mongod -f /mongodb/conf/mongodb.conf --shutdown
使用配置文件启动mongodb
mongod -f /mongodb/conf/mongodb.conf
#登录mongo 需要切换到use admin
db.shutdownServer() 也可关闭mongod
2.yaml格式配置文档
# YAML 配置文件应用
--
NOTE:
YAML does not support tab characters for indentation: use spaces instead.
--系统日志有关
systemLog:
destination: file
path: "/mongodb/log/mongodb.log" --日志位置
logAppend: true --日志以追加模式记录
--数据存储有关
storage:
journal:
enabled: true
dbPath: "/mongodb/data" --数据路径的位置
-- 进程控制
processManagement:
fork: true --后台守护进程
pidFilePath: <string> --pid文件的位置,一般不用配置,可以去掉这行,自动
生成到data中
--网络配置有关
net:
bindIp: <ip> -- 监听地址,如果不配置这行是监听在0.0.0.0
port: <port> -- 端口号,默认不配置端口号,是27017
-- 安全验证有关配置
security:
authorization: enabled --是否打开用户名密码验证
------------------以下是复制集与分片集群有关----------------------
replication:
oplogSizeMB: <NUM>
replSetName: "<REPSETNAME>"
secondaryIndexPrefetch: "all"
sharding:
clusterRole: <string>
archiveMovedChunks: <boolean>
---for mongos only
replication:
localPingThresholdMs: <int>
sharding:
configDB: <string>
---
.........
++++++++++++++++++++++
#编写简易配置档
YAML例子
vim /mongodb/conf/mongo.conf
systemLog:
destination: file
path: "/mongodb/log/mongodb.log"
logAppend: true
storage:
journal:
enabled: true
dbPath: "/mongodb/data/"
processManagement:
fork: true
net:
port: 27017
bindIp: 10.0.0.150,127.0.0.1
#关闭:
mongod -f /mongodb/conf/mongo.conf --shutdown
#开启
mongod -f /mongodb/conf/mongo.conf
[mongod@lss conf]$ mongod -f /mongodb/conf/mongodb.conf
about to fork child process, waiting until server is ready for connections.
forked process: 8703
child process started successfully, parent exiting
++++++++++++++++++++++
#mongodb的关闭方式
mongod -f mongodb.conf --shutdown
#登录mongo
db.shutdownServer() 也可关闭mongod
4.用户基本管理
1.注意事项
用户管理 *****
注意:
验证库,建立用户时use到的库,在使用用户时,要加上验证库才能登陆。
对于管理员用户,必须在admin下创建.
1. 建用户时,use到的库,就是此用户的验证库
2. 登录时,必须明确指定验证库才能登录
3. 通常,管理员用的验证库是admin,普通用户的验证库一般是所管理的库设置为验证库
4. 如果直接登录到数据库,不进行use,默认的验证库是test,不是我们生产建议的.
2. 基本语法
3.用户实例
(1)--创建超级管理员:管理所有数据库(必须use admin再去创建)
$ mongo
> use admin
switched to db admin
> db.createUser(
... {
... user: "root",
... pwd: "root123",
... roles: [ { role: "root", db: "admin" } ]
... }
... )
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
#验证用户
> db.auth('root','root123')
1
(2).创建普通用户
db.createUser(
{
user: "app01",
pwd: "app01",
roles: [ { role: "readWrite" , db: "app" } ]
}
)
> db.auth('app01','app01')
1
(3).开启认证,将以下信息写入配置档中,重起mongodb
配置文件中,加入以下配置
security:
authorization: enabled
重启mongodb
mongod -f /mongodb/conf/mongo.conf --shutdown
mongod -f /mongodb/conf/mongo.conf
(4).重新登录mongo
[root@lss ~]# mongo -u root -p root123 10.0.0.150/admin
MongoDB shell version v4.2.8
connecting to: mongodb://10.0.0.150:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("13dd260c-8b0f-4e6c-b573-534cdbdc8f93") }
MongoDB server version: 4.2.8
#查看用户:
use admin #要查用户需要查好用户对用的
db.system.users.find().pretty()
> db.system.users.find().pretty()
{
"_id" : "admin.root",
"userId" : UUID("32c5bce8-6bbb-4e4d-be46-35f3d0adcdb6"),
"user" : "root",
"db" : "admin",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "UvY7mHKBVOb6jFDWTvYrIg==",
"storedKey" : "QNaK1pyuQ4wFmjQf91dABFJgWuU=",
"serverKey" : "/iEKzPvH6gb43ZIFeAypcSoUlJo="
},
"SCRAM-SHA-256" : {
"iterationCount" : 15000,
"salt" : "5rclUKutvHdivPkkV5GNhq0txt+PRL3FiqSetQ==",
"storedKey" : "EJJDiRMzEUd0BH1R4uBfaA9QWB4cV6j6fuz+M9L50fI=",
"serverKey" : "uJTtn0d2/L3YtzJjSRC9X/L48AkC+ADZ6yFsZhdpgZM="
}
},
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
{
"_id" : "admin.app01",
"userId" : UUID("3171b30e-1864-4217-a575-41325818535a"),
"user" : "app01",
"db" : "admin",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "4Z6hmuTdAqcpPURUP+Z3Tw==",
"storedKey" : "2laFEA3Jk2Z8GVwUIJUBgSv2bGw=",
"serverKey" : "neMzwFjlw6BkbskSKnHBfU/bO+g="
},
"SCRAM-SHA-256" : {
"iterationCount" : 15000,
"salt" : "rPIdl7z5nUX02p8xXfRrbOuqYLpFSOWz08kg/w==",
"storedKey" : "8P9fn0GONuGXi3cGbu5nDV/AX8vBHYFOaJ2NjR+WR3o=",
"serverKey" : "wsoiuAdTB63UnJB3/c1Ya+B8Yeo5m9vlKsC5gr3Dfoc="
}
},
"roles" : [
{
"role" : "readWrite",
"db" : "app"
}
]
}
(5).创建对app数据库,读、写权限的用户app01:
1.超级管理员用户登陆
mongo -uroot -proot123 admin
2.选择一个验证库
use app #如app库不存在也可以use app库中
3.创建用户
db.createUser(
{
user: "app01",
pwd: "app01",
roles: [ { role: "readWrite" , db: "app" } ]
}
)
mongo -uapp01 -papp01 app
4.创建app数据库读写权限的用户并对test数据库具有读权限:
mongo -uroot -proot123 10.0.0.130/admin
use app
db.createUser(
{
user: "app03",
pwd: "app03",
roles: [ { role: "readWrite", db: "app" },
{ role: "read", db: "test" }
]
}
)
5.查询mongodb中的用户信息
mongo -uroot -proot123 10.0.0.150/admin
show databases;
use amdin;
show tables;
system.user
system.version
db.system.users.find().pretty()
> show databases;
admin 0.000GB
config 0.000GB
local 0.000GB
> use admin;
switched to db admin
> show tables;
system.users
system.version
6.删除用户(root身份登录,use到验证库)
# mongo -uroot -proot123 10.0.0.130/admin
use app
db.dropUser("admin")
4.角色关系
5.MongoDB 基本CRUD
1.通用方法和帮助获取
#a.获取帮助
help
> help
db.help() help on db methods
db.mycoll.help() help on collection methods
sh.help() sharding helpers
rs.help() replica set helpers
db.help();
DB methods:
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command
[just calls db.runCommand(...)]
db.aggregate([pipeline], {options}) - performs a collectionless aggregation
on this database; returns a cursor
db.auth(username, password)
db.cloneDatabase(fromhost) - will only function with MongoDB 4.0 and below
...
> db.t1.help();
DBCollection help
db.t1.find().help() - show DBCursor help
db.t1.bulkWrite( operations, <optional params> ) - bulk execute write
operations, optional parameters are: w, wtimeout, j
db.t1.count( query = {}, <optional params> ) - count the number of documents
that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
...
db.[TAB][TAB]
db.t1.[TAB][TAB]
#举例:
> db.help()
DB methods:
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
db.auth(username, password)
db.cloneDatabase(fromhost) - will only function with MongoDB 4.0 and below
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost) - will only function with MongoDB 4.0 and below
db.createCollection(name, {size: ..., capped: ..., max: ...})
db.createUser(userDocument)
db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
db.currentOp() displays currently executing operations in the db
db.dropDatabase(writeConcern)
db.dropUser(username)
db.eval() - deprecated
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnlock() unlocks server following a db.fsyncLock()
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getLogComponents()
db.getMongo() get the server connection object
db.getMongo().setSlaveOk() allow queries on a replication slave server
db.getName()
db.getProfilingLevel() - deprecated
db.getProfilingStatus() - returns if profiling is on and slow threshold
db.getReplicationInfo()
db.getSiblingDB(name) get the db at the same server as this one
db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
db.hostInfo() get details about the server's host
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.loadServerScripts() loads all the scripts in db.system.js
db.logout()
db.printCollectionStats()
db.printReplicationInfo()
db.printShardingStatus()
db.printSlaveReplicationInfo()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj: 1}
db.serverStatus()
db.setLogLevel(level,<component>)
db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
db.setVerboseShell(flag) display extra information in shell output
db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
db.shutdownServer()
db.stats()
db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
db.version() current version of the server
db.watch() - opens a change stream cursor for a database to report on all changes to its non-system collections.
> rs.help()
rs.status() { replSetGetStatus : 1 } checks repl set status
rs.initiate() { replSetInitiate : null } initiates set with default settings
rs.initiate(cfg) { replSetInitiate : cfg } initiates set with configuration cfg
rs.conf() get the current configuration object from local.system.replset
rs.reconfig(cfg) updates the configuration of a running replica set with cfg (disconnects)
rs.add(hostportstr) add a new member to the set with default attributes (disconnects)
rs.add(membercfgobj) add a new member to the set with extra attributes (disconnects)
rs.addArb(hostportstr) add a new member which is arbiterOnly:true (disconnects)
rs.stepDown([stepdownSecs, catchUpSecs]) step down as primary (disconnects)
rs.syncFrom(hostportstr) make a secondary sync from the given member
rs.freeze(secs) make a node ineligible to become primary for the time specified
rs.remove(hostportstr) remove a host from the replica set (disconnects)
rs.slaveOk() allow queries on secondary nodes
rs.printReplicationInfo() check oplog size and time range
rs.printSlaveReplicationInfo() check replica set members and replication lag
db.isMaster() check who is primary
reconfiguration helpers disconnect from the database so the shell will display
an error, even if the command succeeds.
#b. 常用操作
//查看当前db版本
test> db.version()
//显示当前数据库
test> db
> db.getName()
// 查询所有数据库
test> show dbs
//切换数据库
> use local
// 显示当前数据库状态
查看local数据
test> use local
local> db.stats()
查看当前数据库的连接机器地址
> db.getMongo()
// 指定数据库进行连接:(默认连接本机test数据库)
# mongo 192.168.1.24/admin
[mongod@mongodb ~]$ mongo 192.168.1.24/admin
#c. 库和表的操作
// 建库
use test
// 删除
> db.dropDatabase()
{ "dropped" : "test", "ok" : 1 }
// 创建集合(表)
方法1:
admin> use app #直接usb app,表示切换到app库,如果没有这个库,直接创建,库里有表表中有数据时才可以查到这个库
app> db.createCollection('a')
app> db.createCollection('b')
方法2:当插入一个文档的时候,一个集合就会自动创建。
admin> use app
switched to db app
app> db.c.insert({username:"mongodb"}) #往表中C差入数据,如果表不存在,直接创建,表中有数据可以查到表
WriteResult({ "nInserted" : 1 })
app> show collections
app> db.c.find()
{ "_id" : ObjectId("5743c9a9bf72d9f7b524713d"), "username" : "mongodb" }
// 删除集合
app> use app
switched to db app
app> db.log.drop() //删除集合
// 重命名集合
app> db.log.renameCollection("log1")
2.使用 insert 完成插入操作
操作格式:
db.<集合>.insertOne(<JSON对象>) #db.表名.insert({json对象})
db.<集合>.insertMany([<JSON 1>, <JSON 2>, …<JSON n>])
示例:
db.fruit.insertOne({name: "apple"})
db.fruit.insertMany([
{name: "apple"},
{name: "pear"},
{name: "orange"}
])
批量插入数据:
for(i=0;i<10000;i++){ db.log.insert({"uid":i,"name":"mongodb","age":6,"date":new
Date()}); }
#查看当前表
> show tables;
fruit
> show collections;
fruit
#查看表中内容
> db.fruit.find()
{ "_id" : ObjectId("62357cef2382a7643d8eea8e"), "name" : "apple" }
3.使用 find 查询文档
# 关于 find:
find 是 MongoDB 中查询数据的基本指令,相当于 SQL 中的 SELECT 。
find 返回的是游标。
# find 示例:
db.movies.find( { "year" : 1975 } ) //单条件查询
db.movies.find( { "year" : 1989, "title" : "Batman" } ) //多条件and查询
db.movies.find( { $and : [ {"title" : "Batman"}, { "category" : "action" }] } )
// and的另一种形式
db.movies.find( { $or: [{"year" : 1989}, {"title" : "Batman"}] } ) //多条件or查询
db.movies.find( { "title" : /^B/} ) //按正则表达式查找
4.查询条件对照表
SQL | MQL |
---|---|
a=1 | {a: 1} |
a<>1 | {a: {$ne: 1}} |
a>1 | {a: {$gt: 1}} |
a>=1 | {a: {$gte: 1}} |
a<1 | {a: {$lt: 1}} |
a <= 1 | {a: {$lte: 1}} |
5.查询逻辑对照表
SQL | MQL |
---|---|
a = 1 AND b = 1 | {a: 1, b: 1}或{$and: [{a: 1}, {b: 1}]} |
a = 1 OR b = 1 | {$or: [{a: 1}, {b: 1}]} |
a IS NULL | {a: {$exists: false}} |
a IN (1, 2, 3) | {a: {$in: [1, 2, 3]}} |
6.查询逻辑运算符
● $lt: 存在并小于
● $lte: 存在并小于等于
● $gt: 存在并大于
● $gte: 存在并大于等于
● $ne: 不存在或存在但不等于
● $in: 存在并在指定数组中
● $nin: 不存在或不在指定数组中
● $or: 匹配两个或多个条件中的一个
● $and: 匹配全部条件
7.使用 find 搜索子文档
find 支持使用“field.sub_field”的形式查询子文档。假设有一个文档:
db.fruit.insertOne({
name: "apple",
from: {
country: "China",
province: "Guangdong" }
})
正确写法:
> db.fruit.find({ "from.country" : "China" })
{ "_id" : ObjectId("6235ab212382a7643d8eea8f"), "name" : "apple", "from" : { "country" : "China", "province" : "Guangdong" } }
> db.fruit.find().pretty()
{ "_id" : ObjectId("62357cef2382a7643d8eea8e"), "name" : "apple" }
{
"_id" : ObjectId("6235ab212382a7643d8eea8f"),
"name" : "apple",
"from" : {
"country" : "China",
"province" : "Guangdong"
}
}
> db.fruit.find({ "from.province" : "Guangdong" })
{ "_id" : ObjectId("6235ab212382a7643d8eea8f"), "name" : "apple", "from" : { "country" : "China", "province" : "Guangdong" } }
8. 使用 find 搜索数组
find 支持对数组中的元素进行搜索。假设有一个文档:
db.fruit.insert([
{ "name" : "Apple", color: ["red", "green" ] },
{ "name" : "Mango", color: ["yellow", "green"] }
])
查看单个条件:
db.fruit.find({color: "red"})
查询多个条件:
db.fruit.find({$or: [{color: "red"}, {color: "yellow"}]} )
9.使用 find 搜索数组中的对象
#考虑以下文档,在其中搜索
db.movies.insertOne({
"title" : "Raiders of the Lost Ark",
"filming_locations" : [
{ "city" : "Los Angeles", "state" : "CA", "country" : "USA" },
{ "city" : "Rome", "state" : "Lazio", "country" : "Italy" },
{ "city" : "Florence", "state" : "SC", "country" : "USA" }
]
})
// 查找城市是 Rome 的记录
db.movies.find({"filming_locations.city": "Rome"})
在数组中搜索子对象的多个字段时,如果使用 $elemMatch,它表示必须是同一个
子对象满足多个条件。
考虑以下两个查询:
db.getCollection('movies').find({
"filming_locations.city": "Rome",
"filming_locations.country": "USA"
})
db.movies.insertOne( {
"title" : "11111",
"filming_locations" : [
{ "city" : "bj", "state" : "CA", "country" : "CHN" },
{ "city" : "Rome", "state" : "Lazio", "country" : "Italy" },
{ "city" : "tlp", "state" : "SC", "country" : "USA" }
]
})
db.getCollection('movies').find({
"filming_locations": {
$elemMatch:{"city":"bj", "country": "CHN"}
}
})
10. 控制 find 返回的字段
find 可以指定只返回指定的字段;
● _id字段必须明确指明不返回,否则默认返回;
● 在 MongoDB 中我们称这为投影(projection);
● db.movies.find({},{"_id":0, title:1})
11.使用 remove 删除文档
remove 命令需要配合查询条件使用;
● 匹配查询条件的的文档会被删除;
● 指定一个空文档条件会删除所有文档;
● 以下示例:
db.testcol.remove( { a : 1 } ) // 删除a 等于1的记录
db.testcol.remove( { a : { $lt : 5 } } ) // 删除a 小于5的记录
db.testcol.remove( { } ) // 删除所有记录
db.testcol.remove() //报错
12.使用 update 更新文档
Update 操作执行格式:db.<集合>.update(<查询条件>, <更新字段>)
● 以以下数据为例:
db.fruit.insertMany([
{name: "apple"},
{name: "pear"},
{name: "orange"}
])
db.fruit.updateOne({name: "apple"}, {$set: {from: "China"}})
● 使用 updateOne 表示无论条件匹配多少条记录,始终只更新第一条;
● 使用 updateMany 表示条件匹配多少条就更新多少条;
● updateOne/updateMany 方法要求更新条件部分必须具有以下之一,否则将报错:
• $set/$unset
• $push/$pushAll/$pop
• $pull/$pullAll
• $addToSet
● // 报错
db.fruit.updateOne({name: "apple"}, {from: "China"})
13.使用 update 更新数组
● $push: 增加一个对象到数组底部
● $pushAll: 增加多个对象到数组底部
● $pop: 从数组底部删除一个对象
● $pull: 如果匹配指定的值,从数组中删除相应的对象
● $pullAll: 如果匹配任意的值,从数据中删除相应的对象
● $addToSet: 如果不存在则增加一个值到数组
14.使用 drop 删除集合
● 使用 db.<集合>.drop() 来删除一个集合
● 集合中的全部文档都会被删除
● 集合相关的索引也会被删除
db.colToBeDropped.drop()
15.使用 dropDatabase 删除数据库
● 使用 db.dropDatabase() 来删除数据库
● 数据库相应文件也会被删除,磁盘空间将被释放
use tempDB
db.dropDatabase()
show collections // No collections
show dbs // The db is gone
6.通过python操作mongodb
1.安装 Python MongoDB 驱动程序
在 Python 中使用 MongoDB 之前必须先安装用于访问数据库的驱动程序:
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos•7.repo
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum install -y python3
pip3 install pymongo
在 python 交互模式下导入 pymongo,检查驱动是否已正确安装:
import pymongo
pymongo.version
[root@lss ~]# python3
Python 3.6.8 (default, Nov 16 2020, 16:55:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> pymongo.version
'4.0.2'
>>>
2.创建连接
确定 MongoDB 连接串使用驱动连接到 MongoDB 集群只需要指定 MongoDB 连接字符串即可。其基本格式可
以参考文档: Connection String URI Format 最简单的形式是mongodb://数据库服务器主机地址:端口号
如:mongodb://127.0.0.1:27017
● 初始化数据库连接
from pymongo import MongoClient
uri = "mongodb://root:root123@10.0.0.150:27017"
client = MongoClient(uri)
client
3.数据库操作:插入数据
初始化数据库和集合
db = client["eshop"]
user_coll = db["users"]
插入一条新的用户数据
new_user = {"username": "nina", "password": "xxxx", "email":"123456@qq.com "}
result = user_coll.insert_one(new_user)
result
[root@lss ~]# mongo -u root -p root123 admin
> use eshop
switched to db eshop
> show tables;
users
> db.users.find()
{ "_id" : ObjectId("6235e1bd6f009bc34f5a7797"), "username" : "nina", "password" : "xxxx", "email" : "123456@qq.com " }
7.MongoDB RS(Replica Set)
1.复制集的作用
MongoDB 复制集的主要意义在于实现服务高可用,它的现实依赖于两个方面的功能:
• 数据写入时将数据迅速复制到另一个独立节点上
• 在接受写入的节点发生故障时自动选举出一个新的替代节点
在实现高可用的同时,复制集实现了其他几个附加作用:
• 数据分发:将数据从一个区域复制到另一个区域,减少另一个区域的读延迟
• 读写分离:不同类型的压力分别在不同的节点上执行
• 异地容灾:在数据中心故障时候快速切换到异地
2.典型复制集结构
PSS 架构:一主两从(3台机器)
PSA 架构:一主一从一投票(3台机器)
一个典型的复制集由3个以上具有投票权的节点组成,包括:
• 一个主节点(PRIMARY):接受写入操作和选举时投票
• 两个(或多个)从节点(SECONDARY):复制主节点上的新数据和选举时投票
• Arbiter(投票节点)
3.数据是如何复制的
当一个修改操作,无论是插入、更新或删除,到达主节点时,它对数据的操作将被记录下来(经过一些必要的转换),这些记录称为 oplog。
从节点通过在主节点上打开一个 tailable 游标不断获取新进入主节点的 oplog,并在自己的数据上回放,以此保持跟主节点的数据一致。
4.通过选举完成故障恢复
具有投票权的节点之间两两互相发送心跳;
● 当5次心跳未收到时判断为节点失联;
● 如果失联的是主节点,从节点会发起选举,选出新的主节点;
● 如果失联的是从节点则不会产生新的选举;
● 选举基于 RAFT 一致性算法实现,选举成功的必要条件是大多数投票节点存活;
5.影响选举的因素
整个集群必须有大多数节点存活;被选举为主节点的节点必须:
• 能够与多数节点建立连接
• 具有较新的 oplog
• 具有较高的优先级(如果有配置)
6.常见选项
复制集节点有以下常见的选配项:
• 是否具有投票权(v 参数):有则参与投票;
• 优先级(priority 参数):优先级越高的节点越优先成为主节点。优先级为0的节点无法成为主节点;
• 隐藏(hidden 参数):复制数据,但对应用不可见。隐藏节点可以具有投票仅,但优先级必须为0;
• 延迟(slaveDelay 参数):复制 n 秒之前的数据,保持与主节点的时间差。
7.复制集注意事项
● 关于硬件:
• 因为正常的复制集节点都有可能成为主节点,它们的地位是一样的,因此硬件配置上必须一致;
• 为了保证节点不会同时宕机,各节点使用的硬件必须具有独立性。
● 关于软件:
• 复制集各节点软件版本必须一致,以避免出现不可预知的问题。
● 增加节点不会增加系统写性能!
8.Replcation Set配置过程详解
1.规划
三个以上的mongodb节点(或多实例)
多实例:
(1)多个端口:28017、28018、28019、28020
(2)多套目录:
su - mongod
mkdir -p /mongodb/28017/conf /mongodb/28017/data /mongodb/28017/log
mkdir -p /mongodb/28018/conf /mongodb/28018/data /mongodb/28018/log
mkdir -p /mongodb/28019/conf /mongodb/28019/data /mongodb/28019/log
mkdir -p /mongodb/28020/conf /mongodb/28020/data /mongodb/28020/log
(3)配置文件内容准备
cat > /mongodb/28017/conf/mongod.conf <<EOF
systemLog:
destination: file
path: /mongodb/28017/log/mongodb.log
logAppend: true
storage:
journal:
enabled: true
dbPath: /mongodb/28017/data
directoryPerDB: true
#engine: wiredTiger 引擎信息
wiredTiger:
engineConfig:
cacheSizeGB: 1
directoryForIndexes: true
collectionConfig:
blockCompressor: zlib
indexConfig:
prefixCompression: true
processManagement:
fork: true
net:
port: 28017
bindIp: 10.0.0.150,127.0.0.1
replication:
oplogSizeMB: 2048
replSetName: my_repl #集群名称(增减都是连接这个名称)
EOF
\cp /mongodb/28017/conf/mongod.conf /mongodb/28018/conf/
\cp /mongodb/28017/conf/mongod.conf /mongodb/28019/conf/
\cp /mongodb/28017/conf/mongod.conf /mongodb/28020/conf/
sed 's#28017#28018#g' /mongodb/28018/conf/mongod.conf -i
sed 's#28017#28019#g' /mongodb/28019/conf/mongod.conf -i
sed 's#28017#28020#g' /mongodb/28020/conf/mongod.conf -i
------------------------------------------------------------
(4)启动多个实例备用
mongod -f /mongodb/28017/conf/mongod.conf
mongod -f /mongodb/28018/conf/mongod.conf
mongod -f /mongodb/28019/conf/mongod.conf
mongod -f /mongodb/28020/conf/mongod.conf
2.配置复制集(两种方式PSS/PSA)
(1)连接上一个节点
mongo --port 28017/mongo --port 28018
use admin
(2)1主2从,从库普通从库(PSS)
config = {_id: 'my_repl', members: [
{_id: 0, host: '10.0.0.150:28017'},
{_id: 1, host: '10.0.0.150:28018'},
{_id: 2, host: '10.0.0.150:28019'}]
}
rs.initiate(config)
my_repl:PRIMARY> #为主节点
my_repl:SECONDARY> #为从节点
(3)1主1从1个arbiter(PSA)
config = {_id: 'my_repl', members: [
{_id: 0, host: '10.0.0.150:28017'},
{_id: 1, host: '10.0.0.150:28018'},
{_id: 2, host: '10.0.0.150:28019',"arbiterOnly":true}]
}
rs.initiate(config)
3.复制集测试
#主库创建一个表为Movies,默认情况下,只有主库可读写,从库不可以做任何读写,除非设置好
#先创建一个test 库
use test
db.movies.insert([ { "title" : "Jaws", "year" : 1975,
"imdb_rating" : 8.1 },
... { "title" : "Batman", "year" : 1989, "imdb_rating" : 7.6 },
... ] );
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
my_repl:PRIMARY> show tables;
movies
#查询从库是否有相关信息,从而验证主从复制是否从功
注:在mongodb复制集当中,默认从库不允许读写。
rs.slaveOk(); #打开从库读功能
my_repl:SECONDARY> db.movies.find().pretty();
my_repl:SECONDARY> rs.slaveOk();
my_repl:SECONDARY> show tables;
movies
my_repl:SECONDARY> db.movies.find()
{ "_id" : ObjectId("6236ccb0010577ebf1729fad"), "title" : "Jaws", "year" : 1975, "imdb_rating" : 8.1 }
{ "_id" : ObjectId("6236ccb0010577ebf1729fae"), "title" : "Batman", "year" : 1989, "imdb_rating" : 7.6 }
4.复制集管理操作
#(1)查看复制集状态:
rs.status(); //查看整体复制集状态
############################################
my_repl:PRIMARY> rs.status()
{
"set" : "my_repl",
"date" : ISODate("2022-03-20T07:38:45.198Z"),
"myState" : 1,
"term" : NumberLong(1),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"majorityVoteCount" : 2,
"writeMajorityCount" : 2,
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1647761922, 1),
"t" : NumberLong(1)
},
"lastCommittedWallTime" : ISODate("2022-03-20T07:38:42.135Z"),
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1647761922, 1),
"t" : NumberLong(1)
},
"readConcernMajorityWallTime" : ISODate("2022-03-20T07:38:42.135Z"),
"appliedOpTime" : {
"ts" : Timestamp(1647761922, 1),
"t" : NumberLong(1)
},
"durableOpTime" : {
"ts" : Timestamp(1647761922, 1),
"t" : NumberLong(1)
},
"lastAppliedWallTime" : ISODate("2022-03-20T07:38:42.135Z"),
"lastDurableWallTime" : ISODate("2022-03-20T07:38:42.135Z")
},
"lastStableRecoveryTimestamp" : Timestamp(1647761912, 1),
"lastStableCheckpointTimestamp" : Timestamp(1647761912, 1),
"electionCandidateMetrics" : {
"lastElectionReason" : "electionTimeout",
"lastElectionDate" : ISODate("2022-03-20T05:46:30.828Z"),
"electionTerm" : NumberLong(1),
"lastCommittedOpTimeAtElection" : {
"ts" : Timestamp(0, 0),
"t" : NumberLong(-1)
},
"lastSeenOpTimeAtElection" : {
"ts" : Timestamp(1647755179, 1),
"t" : NumberLong(-1)
},
"numVotesNeeded" : 2,
"priorityAtElection" : 1,
"electionTimeoutMillis" : NumberLong(10000),
"numCatchUpOps" : NumberLong(0),
"newTermStartDate" : ISODate("2022-03-20T05:46:30.844Z"),
"wMajorityWriteAvailabilityDate" : ISODate("2022-03-20T05:46:31.989Z")
},
"members" : [
{
"_id" : 0, #节点1
"name" : "10.0.0.150:28017",
"health" : 1, #健康状况
"state" : 1, #state=1为主节点,state=2为从节点
"stateStr" : "PRIMARY",
"uptime" : 13371,
"optime" : { #日志版本信息,可以查看从库信息是否一至,一至表示同步完成
"ts" : Timestamp(1647761922, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2022-03-20T07:38:42Z"),
"syncingTo" : "",
"syncSourceHost" : "",