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

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
日志服务 SLS,月写入数据量 50GB 1个月
简介: 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
目录
相关文章
|
3天前
|
Linux C语言
成功解决 在Linux CentOS 7 中安装gcc
这篇文章介绍了如何在Linux CentOS 7系统中安装gcc (g++) 8工具集。由于CentOS 7默认的gcc版本是4.8,而这个版本与Qt 5.14、Qt 5.15或更高版本不兼容,可能会导致编译时出现系统头文件错误。文章中提到,即使在项目配置中添加了`CONFIG+=c++11`,如果仍然报错,那么很可能是gcc版本的问题。为了解决这个问题,文章提供了使用CentOS的Software Collections (scl)来安装更新版本的gcc的步骤。
成功解决 在Linux CentOS 7 中安装gcc
|
2天前
|
关系型数据库 Java MySQL
Linux安装JDK1.8 & tomcat & MariaDB(MySQL删减版)
本教程提供了在Linux环境下安装JDK1.8、Tomcat和MariaDB的详细步骤。这三个组件的组合为Java Web开发和部署提供了一个强大的基础。通过遵循这些简单的指导步骤,您可以轻松建立起一个稳定、高效的开发和部署环境。希望这个指导对您的开发工作有所帮助。
20 8
|
4天前
|
Linux Python
Linux 升级安装 Python 3
Linux 升级安装 Python 3
11 2
|
4天前
|
NoSQL Ubuntu MongoDB
在Ubuntu 16.04上安装和保护MongoDB的方法
在Ubuntu 16.04上安装和保护MongoDB的方法
9 1
|
4天前
|
Linux 网络安全 Python
Linux离线安装Python时ssh和hashlib死活安装不上的解决方案
本文提供了Linux环境下离线安装Python时遇到的"ImportError: No module named _ssl"和"ERROR:root:code for hash md5|sha1|sha224|sha256|sha384|sha512 was not found"两个问题的解决方案,通过设置OpenSSL环境变量和编辑Python源码配置文件来解决。
8 1
|
4天前
|
存储 NoSQL Java
使用redis进行手机验证码的验证、每天只能发送三次验证码 (redis安装在虚拟机linux系统中)
该博客文章展示了如何在Linux虚拟机上使用Redis和Jedis客户端实现手机验证码的验证功能,包括验证码的生成、存储、验证以及限制每天发送次数的逻辑,并提供了测试结果截图。
使用redis进行手机验证码的验证、每天只能发送三次验证码 (redis安装在虚拟机linux系统中)
|
4天前
|
Linux
虚拟机安装Linux系统的网络配置
该博客文章提供了解决虚拟机中Linux系统网络问题的多种方法,包括重置网络服务、修改网络配置文件、使用不同网络模式等,以确保虚拟机能够成功连接到网络。
虚拟机安装Linux系统的网络配置
|
3天前
|
机器学习/深度学习 Linux Shell
超详细的Linux-Conda环境安装教程
超详细的Linux-Conda环境安装教程
|
4天前
|
Oracle Java 关系型数据库
简单记录在Linux上安装JDK环境的步骤,以及解决运行Java程序时出现Error Could not find or load main class XXX问题
本文记录了在Linux系统上安装JDK环境的步骤,并提供了解决运行Java程序时出现的"Error Could not find or load main class XXX"问题的方案,主要是通过重新配置和刷新JDK环境变量来解决。
12 0
|
4天前
|
Linux 数据安全/隐私保护 Docker
MQTT(EMQX) - Linux CentOS Docker 安装
MQTT(EMQX) - Linux CentOS Docker 安装
20 0