MongoDB的「Linux」安装及基本使用

0. 写在前面
- Linux:
Ubuntu Kylin16.04
- 集群搭建方式:
伪分布式
- MongoDB:
MongoDB3.2.7
- 部署方式:
单机部署
1. 下载并安装MongoDB
https://www.mongodb.com/try/download/community
选择Community Server
下载即可
| root@node01:~$ tar -zxvf mongodb-linux-x86_64-ubuntu1604-4.2.8.tgz -C /usr/local |
| root@node01:~$ vim ./.bashrc |
| |
| export MONGODB_HOME=/usr/local/mongodb-3.2.7 |
| export PATH=$PATH:$MONGODB_HOME/bin |
| root@node01:~$ source ./.bashrc |
| root@node01:~$ mongo --version |
| MongoDB shell version: 3.2.7 |
2. 启动方式
2.1 直接启动
提前创建MongoDB服务的数据存储目录
和日志目录
| root@node01:/usr/local/mongodb-3.2.7$ mkdir -p ./data/db |
| root@node01:/usr/local/mongodb-3.2.7$ mkdir -p ./log |
命令行启动「–fork」
| root@node01:/usr/local/mongodb-3.2.7$ mongod --dbpath data/db --logpath log/mongod.log --fork |
停止服务使用「–shutdown」
| root@node01:/usr/local/mongodb-3.2.7$ mongod --dbpath data/db --logpath log/mongod.log --shutdown |
2.2 以「配置文件」方式启动
有两种方式
2.2.1 使用默认配置文件
默认配置文件是:/etc/mongod.conf
| root@node01:/usr/local/mongodb-3.2.7$ mongod -f /etc/mongod.conf |
2.2.2 自定义配置文件
| |
| mkdir -p /mongodb/single/data/db |
| |
| mkdir -p /mongodb/single/log |
| vim /mongodb/single/mongod.conf |
配置文件的内容如下:
| systemLog: |
| |
| |
| destination: file |
| |
| path: "/mongodb/single/log/mongod.log" |
| |
| logAppend: true |
| storage: |
| |
| |
| dbPath: "/mongodb/single/data/db" |
| journal: |
| |
| enabled: true |
| processManagement: |
| |
| fork: true |
| net: |
| |
| bindIp: localhost |
| |
| |
| port: 27017 |
| root@node01:/usr/local/mongodb-3.2.7$ mongod --config /mongodb/single/mongod.conf |
| about to fork child process, waiting until server is ready for connections. |
| forked process: 3286 |
| child process started successfully, parent exiting |
强烈建议自己创建配置文件,使用第二种方式启动服务,本文讲述均以此种方式
| root@node01:/usr/local/mongodb-3.2.7$ ps -ef | grep mongod |
| root 3286 1 0 16:35 ? 00:00:23 /usr/local/mongodb-3.2.7/bin/mongod -f /mongodb/single/mongod.conf |
| root 3421 3086 0 17:30 pts/0 00:00:00 grep --color=auto mongod |
| |
| |
3. 自定义配置文件启动MongoDB服务失败解决方法
| 解决“Error parsing YAML config file: yaml-cpp: error at line 2, column 13: illegal map value”(安装服务) |
| try '/usr/local/mongodb-3.2.7/bin/mongod |
yaml前置芝士
YAML的基本语法规则
- 大小写敏感
- 使用缩进表示层级关系
- 缩进时不允许使用Tab键,只允许使用空格。(可以将你的ide的tab按键输出替换成4个空格)
- 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
- '#'表示注释
第三小点尤为重要,不要使用Tab键
实现缩进,请用空格
实现缩进
YAML格式使用KV方式<key>: <value>
表示,以空格作为缩进,若value存在,在之后的:
后面,即value值的前面需要
紧跟一个空格;如:destination: file
4. 基本使用
| > use dbtest |
| > show collections |
| > db.colltest.find() |
| { "_id" : 11, "item" : "Pencil", "qty" : 50, "type" : "no.2" } |
| { "_id" : ObjectId("6329f410665960c08e8943bf"), "_item" : "pen", "qty" : 20 } |
| { "_id" : ObjectId("6329f410665960c08e8943c0"), "item" : "eraser", "qty" : 25 } |
| > db.help() |
| DB methods: |
| db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ] |
| db.auth(username, password) |
| db.cloneDatabase(fromhost) |
| db.commandHelp(name) returns the help for the command |
| db.copyDatabase(fromdb, todb, fromhost) |
| db.createCollection(name, ) |
| db.createUser(userDocument) |
| db.currentOp() displays currently executing operations in the db |
| db.dropDatabase() |
| 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.getPrevError() |
| 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.dropUser(username) |
| db.repairDatabase() |
| db.resetError() |
| db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into |
| db.serverStatus() |
| db.setLogLevel(level,<component>) |
| db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all |
| db.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the db |
| db.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the db |
| db.setVerboseShell(flag) display extra information in shell output |
| db.shutdownServer() |
| db.stats() |
| db.version() current version of the server |
停止服务的方式有两种:快速关闭
和标准关闭
,下面依次说明:
(一)快速关闭方法(快速,简单,数据可能会出错)
目标:通过系统的kill命令直接杀死进程:
杀完要检查一下,避免有的没有杀掉。
【补充】
如果一旦是因为数据损坏,则需要进行如下操作(了解):
1)删除lock文件:
| rm -f /mongodb/single/data/db/*.lock |
2)修复数据:
| /usr/local/mongdb-3.2.7/bin/mongod --repair --dbpath=/mongodb/single/data/db |
(二)标准的关闭方法(数据不容易出错,但麻烦):
目标:通过mongo客户端中的shutdownServer命令来关闭服务
主要的操作
| |
| mongo --port 27017 |
| |
| use admin |
| |
| db.shutdownServer() |
需要使用admin数据库,官方说明如下:
| db.shutdownServer() |
| Shuts down the current mongod or mongos process cleanly and safely. |
| This operation fails when the current database is not the admin database. |
| This command provides a wrapper around the shutdown command. |
| > db.shutdownServer() |
| server should be down... |
| 2022-09-20T17:37:40.772+0800 I NETWORK [thread1] trying reconnect to 127.0.0.1:27017 (127.0.0.1) failed |
| 2022-09-20T17:37:40.773+0800 W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused |
| 2022-09-20T17:37:40.773+0800 I NETWORK [thread1] reconnect 127.0.0.1:27017 (127.0.0.1) failed failed |
注意:
这里failed不是停止服务失败
见下方MongoDB Community的论坛回答
链接
https://www.mongodb.com/community/forums/t/db-shutdownserver-giving-connection-error/29333
| There is no problem here. You shutdown the server. It is normal that the mongo cannot connect to the server, it is now down. Just exit the shell. |
这里没有问题。你关闭了服务器。 mongo连接不上服务器是正常的,现在宕机了。只需退出外壳。
5. 参考
| https://www.runoob.com/mongodb/mongodb-linux-install.html |
| https://www.runoob.com/w3cnote/yaml-intro.html |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)