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

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

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


ad61faea5ea343a28fe757431d8517ed.jpeg



0. 写在前面

  • Linux: Ubuntu Kylin16.04 
  • 集群搭建方式: 伪分布式 
  • MongoDB: MongoDB3.2.7 
  • 部署方式: 单机部署 


1. 下载并安装MongoDB


  • [官网下载](https://www.mongodb.com/try/download/community)

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


  • 添加如下内容
#MongoDBexportMONGODB_HOME=/usr/local/mongodb-3.2.7
exportPATH=$PATH:$MONGODB_HOME/bin


  • 记得source使环境变量生效
root@node01:~$ source ./.bashrc


  • 查看版本号
root@node01:~$ mongo--versionMongoDB 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:
#MongoDB发送所有日志输出的目标指定为文件# #The path of the log file to which mongod or mongos should send all diagnostic logging information  destination: file
#mongod或mongos应向其发送所有诊断日志记录信息的日志文件的路径  path: "/mongodb/single/log/mongod.log"#当mongos或mongod实例重新启动时,mongos或mongod会将新条目附加到现有日志文件的末尾。  logAppend: truestorage:
#mongod实例存储其数据的目录。storage.dbPath设置仅适用于mongod。##The directory where the mongod instance stores its data.Default Value is "/data/db".  dbPath: "/mongodb/single/data/db"  journal:
#启用或禁用持久性日志以确保数据文件保持有效和可恢复。    enabled: trueprocessManagement:
#启用在后台运行mongos或mongod进程的守护进程模式。  fork: truenet:
#服务实例绑定的IP,默认是localhost  bindIp: localhost
#bindIp#绑定的端口,默认是27017  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: 3286child process started successfully, parent exiting


强烈建议自己创建配置文件,使用第二种方式启动服务,本文讲述均以此种方式


- 查看服务进程

root@node01:/usr/local/mongodb-3.2.7$ ps-ef | grep mongod
root       32861016:35 ?        00:00:23 /usr/local/mongodb-3.2.7/bin/mongod -f /mongodb/single/mongod.conf
root       34213086017: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 --help' for more information
  • 检查配置文件是否写错
  • yaml格式问题

yaml前置芝士

YAML的基本语法规则:

  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格。(可以将你的ide的tab按键输出替换成4个空格)
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • # 表示注释


第三小点尤为重要, 不要使用Tab键 实现缩进,请用 空格 实现缩进


YAML格式使用KV方式 : 表示,以空格作为缩进,若value存在,在之后的 : 后面,即value值的前面需要

紧跟一个空格;如: destination: file 


4. 基本使用

  • 查看数据库/集合
> show dbs;
local  0.000GB


> 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.dropDatabase()


  • 数据库操作
> 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, { size : ..., capped : ..., max : ... } )
  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 { cmdObj : 1 }
  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命令来关闭服务

主要的操作

//客户端登录服务,注意,这里通过localhost登录,如果需要远程登录,必须先登录认证才行。
mongo --port27017//#切换到admin库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



目录
相关文章
|
6月前
|
Ubuntu Linux
计算机基础知识:linux系统怎么安装?
在虚拟机软件中创建一个新的虚拟机,并选择相应操作系统类型和硬盘空间大小等参数。将下载的 ISO 镜像文件加载到虚拟机中。启动虚拟机,进入安装界面,并按照步骤进行安装。安装完成后,可以在虚拟机中使用 Linux 系统。
|
4月前
|
安全 Linux iOS开发
Nessus Professional 10.10 Auto Installer for RHEL 10, AlmaLinux 10, Rocky Linux 10 - Nessus 自动化安装程序
Nessus Professional 10.10 Auto Installer for RHEL 10, AlmaLinux 10, Rocky Linux 10 - Nessus 自动化安装程序
283 6
Nessus Professional 10.10 Auto Installer for RHEL 10, AlmaLinux 10, Rocky Linux 10 - Nessus 自动化安装程序
|
4月前
|
NoSQL Ubuntu MongoDB
在Ubuntu 22.04上安装MongoDB 6.0的步骤
这些步骤应该可以在Ubuntu 22.04系统上安装MongoDB 6.0。安装过程中,如果遇到任何问题,可以查阅MongoDB的官方文档或者Ubuntu的相关帮助文档,这些资源通常提供了解决特定问题的详细指导。
452 18
|
5月前
|
NoSQL IDE MongoDB
Studio 3T 2025.17 (macOS, Linux, Windows) - MongoDB 的终极 GUI、IDE 和 客户端
Studio 3T 2025.17 (macOS, Linux, Windows) - MongoDB 的终极 GUI、IDE 和 客户端
362 1
Studio 3T 2025.17 (macOS, Linux, Windows) - MongoDB 的终极 GUI、IDE 和 客户端
|
4月前
|
消息中间件 Kafka Linux
Linux下安装Kafka 3.9.1
本文介绍Kafka 3.9.1版本的安装与配置,包括通过ZooKeeper或KRaft模式启动Kafka。涵盖环境变量设置、日志路径修改、集群UUID生成、存储格式化及服务启停操作,适用于Linux环境下的部署实践。
505 0
|
6月前
|
网络协议 关系型数据库 Linux
【App Service Linux】在Linux App Service中安装 tcpdump 并抓取网络包
在App Service for Linux环境中,无法像Windows一样直接使用网络排查工具抓包。本文介绍了如何通过TCPDUMP在Linux环境下抓取网络包,包括SSH进入容器、安装tcpdump、执行抓包命令及下载分析文件的完整操作步骤。
302 5
|
6月前
|
弹性计算 安全 Linux
阿里云服务器ECS安装宝塔Linux面板、安装网站(新手图文教程)
本教程详解如何在阿里云服务器上安装宝塔Linux面板,涵盖ECS服务器手动安装步骤,包括系统准备、远程连接、安装命令执行、端口开放及LNMP环境部署,手把手引导用户快速搭建网站环境。
|
6月前
|
Ubuntu 安全 Linux
Linux这5款微型发行版,体积小+精简,比win7运行还快,值得安装
以上5款微型发行版体积小且精简,如果你有台旧电脑,不妨试试?
|
6月前
|
安全 Ubuntu Linux
如何安装Linux操作系统?
此时,您可以选择重新启动计算机,然后从硬盘上的Linux系统启动。以上是一个大致的安装过程。请注意,不同的Linux发行版可能会在细节上有所差异,因此在进行安装之前,请确保您阅读并理解了相应发行版的安装指南或文档。