Linux 安装 MongoDB

下载 MongoDB

使用浏览器访问 https://www.mongodb.com/try/download/community-kubernetes-operator  地址,根据自己的需要选择合适的版本,笔者这里选择 Ubuntu 系统版本的安装包,安装版本 5.0.20,如下图:

Linux 安装 MongoDB

下载地址:https://repo.mongodb.org/apt/ubuntu/dists/focal/mongodb-org/5.0/multiverse/binary-amd64/mongodb-org-server_5.0.20_amd64.deb 

采用 wget 命令下载安装包,如下:

hxstrive@localhost:~/Desktop$ sudo wget https://repo.mongodb.org/apt/ubuntu/dists/focal/mongodb-org/5.0/multiverse/binary-amd64/mongodb-org-server_5.0.20_amd64.deb
[sudo] password for hxstrive:
--2023-08-18 13:41:17--  https://repo.mongodb.org/apt/ubuntu/dists/focal/mongodb-org/5.0/multiverse/binary-amd64/mongodb-org-server_5.0.20_amd64.deb
Resolving repo.mongodb.org (repo.mongodb.org)... 18.239.199.99, 18.239.199.6, 18.239.199.15, ...
Connecting to repo.mongodb.org (repo.mongodb.org)|18.239.199.99|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 26634032 (25M)
Saving to: ‘mongodb-org-server_5.0.20_amd64.deb.1’

mongodb-org-server_5.0.20_amd 100%[=================================================>]  25.40M  3.70MB/s    in 7.9s    

2023-08-18 13:41:26 (3.20 MB/s) - ‘mongodb-org-server_5.0.20_amd64.deb.1’ saved [26634032/26634032]

安装 MongoDB

使用 dpkg 命令安装 MongoDB,如下:

hxstrive@localhost:~/Desktop$ sudo dpkg -i mongodb-org-server_5.0.20_amd64.deb
[sudo] password for hxstrive:
(Reading database ... 267639 files and directories currently installed.)
Preparing to unpack mongodb-org-server_5.0.20_amd64.deb ...
Unpacking mongodb-org-server (5.0.20) over (5.0.20) ...
Setting up mongodb-org-server (5.0.20) ...
Processing triggers for man-db (2.9.4-2) ...

没有任何错误提示,安装成功。

运行 MongoDB

输入 mongod 命令运行 MongoDB,如下:

hxstrive@localhost:~/Desktop$ mongod
{"t":{"$date":"2023-08-18T14:38:56.006+08:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"-","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":13},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":13},"outgoing":{"minWireVersion":0,"maxWireVersion":13},"isInternalClient":true}}}
{"t":{"$date":"2023-08-18T14:38:56.007+08:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"main","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2023-08-18T14:38:56.007+08:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2023-08-18T14:38:56.007+08:00"},"s":"I",  "c":"NETWORK",  "id":4648601, "ctx":"main","msg":"Implicit TCP FastOpen unavailable. If TCP FastOpen is required, set tcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize."}
{"t":{"$date":"2023-08-18T14:38:56.009+08:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2023-08-18T14:38:56.009+08:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","ns":"config.tenantMigrationDonors"}}
{"t":{"$date":"2023-08-18T14:38:56.009+08:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"main","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","ns":"config.tenantMigrationRecipients"}}
{"t":{"$date":"2023-08-18T14:38:56.009+08:00"},"s":"I",  "c":"CONTROL",  "id":5945603, "ctx":"main","msg":"Multi threading initialized"}
{"t":{"$date":"2023-08-18T14:38:56.010+08:00"},"s":"I",  "c":"CONTROL",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":9485,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"localhost"}}
{"t":{"$date":"2023-08-18T14:38:56.010+08:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"5.0.20","gitVersion":"2cd626d8148120319d7dca5824e760fe220cb0de","openSSLVersion":"OpenSSL 1.1.1l  24 Aug 2021","modules":[],"allocator":"tcmalloc","environment":{"distmod":"ubuntu2004","distarch":"x86_64","target_arch":"x86_64"}}}}
{"t":{"$date":"2023-08-18T14:38:56.010+08:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Ubuntu","version":"21.10"}}}
{"t":{"$date":"2023-08-18T14:38:56.010+08:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{}}}
{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"E",  "c":"CONTROL",  "id":20557,   "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","attr":{"error":"NonExistentPath: Data directory /data/db not found. Create the missing directory or specify another path using (1) the --dbpath command line option, or (2) by adding the 'storage.dbPath' option in the configuration file."}}
{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"I",  "c":"REPL",     "id":4784900, "ctx":"initandlisten","msg":"Stepping down the ReplicationCoordinator for shutdown","attr":{"waitTimeMillis":15000}}
{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"I",  "c":"COMMAND",  "id":4784901, "ctx":"initandlisten","msg":"Shutting down the MirrorMaestro"}
{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"I",  "c":"SHARDING", "id":4784902, "ctx":"initandlisten","msg":"Shutting down the WaitForMajorityService"}
{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"I",  "c":"NETWORK",  "id":20562,   "ctx":"initandlisten","msg":"Shutdown: going to close listening sockets"}
{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"I",  "c":"NETWORK",  "id":4784905, "ctx":"initandlisten","msg":"Shutting down the global connection pool"}
{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"I",  "c":"CONTROL",  "id":4784906, "ctx":"initandlisten","msg":"Shutting down the FlowControlTicketholder"}
{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"I",  "c":"-",        "id":20520,   "ctx":"initandlisten","msg":"Stopping further Flow Control ticket acquisitions."}
{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"I",  "c":"NETWORK",  "id":4784918, "ctx":"initandlisten","msg":"Shutting down the ReplicaSetMonitor"}
{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"I",  "c":"SHARDING", "id":4784921, "ctx":"initandlisten","msg":"Shutting down the MigrationUtilExecutor"}
{"t":{"$date":"2023-08-18T14:38:56.012+08:00"},"s":"I",  "c":"ASIO",     "id":22582,   "ctx":"MigrationUtil-TaskExecutor","msg":"Killing all outstanding egress activity."}
{"t":{"$date":"2023-08-18T14:38:56.012+08:00"},"s":"I",  "c":"COMMAND",  "id":4784923, "ctx":"initandlisten","msg":"Shutting down the ServiceEntryPoint"}
{"t":{"$date":"2023-08-18T14:38:56.012+08:00"},"s":"I",  "c":"CONTROL",  "id":4784925, "ctx":"initandlisten","msg":"Shutting down free monitoring"}
{"t":{"$date":"2023-08-18T14:38:56.012+08:00"},"s":"I",  "c":"CONTROL",  "id":4784927, "ctx":"initandlisten","msg":"Shutting down the HealthLog"}
{"t":{"$date":"2023-08-18T14:38:56.012+08:00"},"s":"I",  "c":"CONTROL",  "id":4784928, "ctx":"initandlisten","msg":"Shutting down the TTL monitor"}
{"t":{"$date":"2023-08-18T14:38:56.012+08:00"},"s":"I",  "c":"CONTROL",  "id":4784929, "ctx":"initandlisten","msg":"Acquiring the global lock for shutdown"}
{"t":{"$date":"2023-08-18T14:38:56.012+08:00"},"s":"I",  "c":"-",        "id":4784931, "ctx":"initandlisten","msg":"Dropping the scope cache for shutdown"}
{"t":{"$date":"2023-08-18T14:38:56.012+08:00"},"s":"I",  "c":"FTDC",     "id":4784926, "ctx":"initandlisten","msg":"Shutting down full-time data capture"}
{"t":{"$date":"2023-08-18T14:38:56.012+08:00"},"s":"I",  "c":"CONTROL",  "id":20565,   "ctx":"initandlisten","msg":"Now exiting"}
{"t":{"$date":"2023-08-18T14:38:56.012+08:00"},"s":"I",  "c":"CONTROL",  "id":23138,   "ctx":"initandlisten","msg":"Shutting down","attr":{"exitCode":100}}

上述的关键信息如下:

{"t":{"$date":"2023-08-18T14:38:56.011+08:00"},"s":"E",  "c":"CONTROL",  "id":20557,   "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","attr":{"error":"NonExistentPath: Data directory /data/db not found. Create the missing directory or specify another path using (1) the --dbpath command line option, or (2) by adding the 'storage.dbPath' option in the configuration file."}}

指出 /data/db 目录不存在,手动创建目录,如下:

# 创建目录
hxstrive@localhost:/$ sudo mkdir -p /data/db
hxstrive@localhost:/$ ll data/
total 12
drwxr-xr-x  3 root root 4096  8月 18 15:03 ./
drwxr-xr-x 21 root root 4096  8月 18 15:03 ../
drwxr-xr-x  2 root root 4096  8月 18 15:03 db/

# 修改目录的所属
hxstrive@localhost:/$ sudo chown -R hxstrive:hxstrive /data
hxstrive@localhost:/$ ll data/
total 12
drwxr-xr-x  3 hxstrive hxstrive 4096  8月 18 15:03 ./
drwxr-xr-x 21 root     root     4096  8月 18 15:03 ../
drwxr-xr-x  2 hxstrive hxstrive 4096  8月 18 15:03 db/

再次执行 mongod 就能正常启动了,但是我们通过 systemctl 查看服务状态,还是未启动成功状态,如下:

hxstrive@localhost:~/Desktop$ sudo systemctl status mongod
○ mongod.service - MongoDB Database Server
    Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
    Active: inactive (dead)
      Docs: https://docs.mongodb.org/manual

这是因为我们直接使用 mongod 命令启动,没有使用 systemctl 命令去启动。

采用 systemctl 启动 MongoDB 服务,如下:

# 启动 MongoDB 服务
hxstrive@localhost:/$ sudo systemctl start mongod
[sudo] password for hxstrive:

# 查看 MongoDB 服务状态
hxstrive@localhost:/$ sudo systemctl status mongod
● mongod.service - MongoDB Database Server
    Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
    Active: active (running) since Fri 2023-08-18 15:10:26 CST; 7s ago
      Docs: https://docs.mongodb.org/manual
  Main PID: 13698 (mongod)
    Memory: 66.0M
       CPU: 1.074s
    CGroup: /system.slice/mongod.service
            └─13698 /usr/bin/mongod --config /etc/mongod.conf

8月 18 15:10:26 localhost systemd[1]: Started MongoDB Database Server.
8月 18 15:10:26 localhost mongod[13698]: {"t":{"$date":"2023-08-18T07:10:26.566Z"},"s":"I",  "c":"CONTROL",  "id":7484500, "ctx":"-","msg":"Environment variable MONGODB_CONFIG_OVER>

从上面输出的信息可知,可执行文件位于 /usr/bin/mongod 路径,配置文件位于 /etc/mongod.conf。

更多 systemctl 命令如下:

#开机启动mongodb
sudo systemctl enable mongod
#启动mongo服务
sudo systemctl start mongod
#关闭mongo服务
sudo systemctl stop mongod
#重启mongodb服务
sudo systemctl restart mongod
#查看mongodb运行状态
sudo systemctl status mongod

连接到 MongoDB

很抱歉,上面的一番操作也仅仅安装了 MongoDB 的服务端,并没有安装客户端,客户端需要我们再次手动去安装,进入官网下载地址,如下图:

Linux 安装 MongoDB

选择 shell 包,下载地址:https://repo.mongodb.org/apt/ubuntu/dists/focal/mongodb-org/5.0/multiverse/binary-amd64/mongodb-org-shell_5.0.20_amd64.deb

第一步:使用 wget 将包下载下来,如下:

hxstrive@localhost:~$ sudo wget https://repo.mongodb.org/apt/ubuntu/dists/focal/mongodb-org/5.0/multiverse/binary-amd64/mongodb-org-shell_5.0.20_amd64.deb
--2023-08-18 14:44:39--  https://repo.mongodb.org/apt/ubuntu/dists/focal/mongodb-org/5.0/multiverse/binary-amd64/mongodb-org-shell_5.0.20_amd64.deb
Resolving repo.mongodb.org (repo.mongodb.org)... 13.225.244.37, 13.225.244.64, 13.225.244.13, ...
Connecting to repo.mongodb.org (repo.mongodb.org)|13.225.244.37|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 14844388 (14M)
Saving to: ‘mongodb-org-shell_5.0.20_amd64.deb’

mongodb-org-shell_5.0.20_amd6 100%[=================================================>]  14.16M  1.02MB/s    in 19s    

2023-08-18 14:45:00 (754 KB/s) - ‘mongodb-org-shell_5.0.20_amd64.deb’ saved [14844388/14844388]

第二步:使用 dpkg 命令安装 MongoDB 客户端,如下:

hxstrive@localhost:~$ sudo dpkg -i mongodb-org-shell_5.0.20_amd64.deb
(Reading database ... 267688 files and directories currently installed.)
Preparing to unpack mongodb-org-shell_5.0.20_amd64.deb ...
Unpacking mongodb-org-shell (5.0.20) ...
Setting up mongodb-org-shell (5.0.20) ...
Processing triggers for man-db (2.9.4-2) ...

第三步:由于我们是在安装 MongoDB 服务的机器上连接 MongoDB,可以直接输入 mongo 命令去连接,不需要输入多余参数,如下:

hxstrive@localhost:/$ mongo
MongoDB shell version v5.0.20
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4dfb4aba-d768-44ae-b18e-d67b207e5956") }
MongoDB server version: 5.0.20
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
---
The server generated these startup warnings when booting:
       2023-08-18T15:04:55.546+08:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
       2023-08-18T15:04:56.390+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
       2023-08-18T15:04:56.390+08:00: This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning
       2023-08-18T15:04:56.390+08:00: Soft rlimits for open file descriptors too low
       2023-08-18T15:04:56.390+08:00:         currentValue: 1024
       2023-08-18T15:04:56.390+08:00:         recommendedMinimum: 64000
---
>

如果看见了上面的提示,则连接成功。

第四步:执行一个插入命令和一个查找命令,如下:

# 插入一个文档到 hxstrive 集合,如果 hxstrive 集合没有 MongoDB 会自动创建
> db.hxstrive.insert({title:"Hello Mongodb"})
WriteResult({ "nInserted" : 1 })

# 查找 hxstrive 集合中的文档
> db.hxstrive.find();
{ "_id" : ObjectId("64df192087bb5cb1d01dedae"), "title" : "Hello Mongodb" }

注意:如果你想远程访问 MongoDB,默认情况下是不能访问的,因为默认绑定的 IP 为 127.0.0.1,禁止远程访问,这是为了安全考虑。当然,我们可以通过编辑 /etc/mongod.conf 配置文件,将绑定 IP 修改为 0.0.0.0,那么任何 IP 均能访问 MongoDB 服务,正式环境不推荐,因为很危险。修改配置如下:

hxstrive@localhost:~$ cat /etc/mongod.conf
# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
 dbPath: /var/lib/mongodb
 journal:
   enabled: true
#  engine:
#  wiredTiger:

# where to write logging data.
systemLog:
 destination: file
 logAppend: true
 path: /var/log/mongodb/mongod.log

# network interfaces
net:
 port: 27017
 bindIp: 0.0.0.0  # 修改这里,你没有看错


# how the process runs

关于更多 MongoDB 的用法,请继续阅读后续章节。

说说我的看法
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
公众号