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

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 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



相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
1天前
|
Oracle 关系型数据库 Linux
SuSE linux server 11通过SAP来安装oracle11g
SuSE linux server 11通过SAP来安装oracle11g
|
1天前
|
Linux C语言
suse linux 11 安装GCC开发环境
suse linux 11 安装GCC开发环境
|
3天前
|
关系型数据库 MySQL Linux
在Linux系统上实现高效安装与部署环境的全方位指南
在Linux系统上实现高效安装与部署环境的全方位指南
|
3天前
|
NoSQL Linux Redis
Redis的介绍,以及Redis的安装(本机windows版,虚拟机Linux版)和Redis常用命令的介绍
Redis的介绍,以及Redis的安装(本机windows版,虚拟机Linux版)和Redis常用命令的介绍
17 0
|
3天前
|
Ubuntu 安全 Linux
linux系统详细安装过程,都在这里了
linux系统详细安装过程,都在这里了
12 0
|
3天前
|
JSON Linux 数据格式
在宝塔Linux中安装Docker
在宝塔Linux中安装Docker
|
3天前
|
运维 监控 安全
2023年最详细的:本地Linux服务器安装宝塔面板,并内网穿透实现公网远程登录
2023年最详细的:本地Linux服务器安装宝塔面板,并内网穿透实现公网远程登录
|
5天前
|
安全 Linux Python
Volatility3内存取证工具安装及入门在Linux下的安装教程
Volatility3内存取证工具安装及入门在Linux下的安装教程
Volatility3内存取证工具安装及入门在Linux下的安装教程
|
5天前
|
关系型数据库 MySQL Linux
Linux CentOs7 安装Mysql(5.7和8.0版本)密码修改 超详细教程
Linux CentOs7 安装Mysql(5.7和8.0版本)密码修改 超详细教程
|
5天前
|
Web App开发 安全 Unix
Linux 配置FTP服务器 + vsftpd服务安装配置 (Good篇)
Linux 配置FTP服务器 + vsftpd服务安装配置 (Good篇)