> For the complete documentation index, see [llms.txt](https://book.bsdcn.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.bsdcn.org/di-33-zhang-shu-ju-ku-guan-li/di-33.5-jie-mongodb.md).

# 33.5 MongoDB

MongoDB 是采用 BSON 格式存储的 NoSQL 文档型数据库，具备动态模式与水平扩展能力。本节说明 FreeBSD 上 MongoDB 8.0 的 pkg 安装、启动配置及基础操作流程。

> **注意**：
>
> 自 2018 年 10 月 16 日起，MongoDB Community Server 的许可证从 AGPL v3 变更为 SSPL（Server Side Public License，服务器端公共许可证）。SSPL 基于 GPL v3 修改而来，要求以服务形式提供 MongoDB 的第三方必须开源其全部服务栈源代码。SSPL 未被 OSI（Open Source Initiative）批准为开源许可证，MongoDB 于 2019 年 3 月撤回了 OSI 审批申请。严格意义上，MongoDB 属于“源码可用”（source-available）软件，而非 OSI 定义下的开源软件。关于 SSPL 下具体允许与禁止的使用方式，请查阅 MongoDB 官方的 SSPL FAQ：<https://www.mongodb.com/legal/licensing/server-side-public-license/faq>。

## 安装

使用 pkg 安装 MongoDB：

```sh
# pkg install mongodb80
```

或者使用 Ports 安装：

```sh
# cd /usr/ports/databases/mongodb80/
# make install clean
```

查看 MongoDB 安装后的说明信息：

```sh
# pkg info -D mongodb80
```

## 服务

安装完成后，启动 MongoDB 服务：

```sh
# service mongod enable   # 设置 MongoDB 服务开机自启
# service mongod start    # 启动 MongoDB 服务
```

## mongosh（MongoDB 官方 Shell CLI）

MongoDB 6.0 及更高版本不再包含传统的 `mongo` 命令行工具，取而代之的是官方的 `mongosh`。在 FreeBSD Ports 源中已经提供 `mongosh`，无需额外操作。

### 安装 mongosh

使用 pkg 安装：

```sh
# pkg install mongosh
```

或者使用 Ports 安装：

```sh
# cd /usr/ports/databases/mongosh/
# make install clean
```

### 测试连接 MongoDB

使用 `mongosh` 连接到本地 MongoDB 服务：

```sh
# mongosh mongodb://127.0.0.1:27017
Current Mongosh Log ID:	67bca91ccf5bbd1a232d5665
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.5
Using MongoDB:		8.0.4
Using Mongosh:		2.2.5

For mongosh info see: https://docs.mongodb.com/mongodb-shell/


To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.

------
   The server generated these startup warnings when booting
   2025-02-25T01:08:25.311+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------

test>
```

## 配置文件

相关项目文件结构：

```sh
/
└── usr/
    ├── local/
    │   └── etc/
    │       ├── mongodb.conf        # MongoDB 配置文件
    │       └── mongodb.conf.sample # MongoDB 配置文件示例
    └── ports/
        └── databases/
            ├── mongodb80/  # MongoDB 8.0 Port
            └── mongosh/    # MongoDB Shell Port
```

如需进一步配置 MongoDB，可以修改其配置文件。

MongoDB 8.0 的配置文件位于 **/usr/local/etc/mongodb.conf**，配置模板文件位于 **/usr/local/etc/mongodb.conf.sample**。

## 创建用户和密码

MongoDB 默认不启用访问控制，任何人均可连接和操作数据库。建议创建用户并设置密码。

使用 `mongosh` 连接本地 MongoDB 服务：

```sql
# mongosh mongodb://127.0.0.1:27017
Current Mongosh Log ID:	67bcb0e5337ba1c7d62d5665
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.5
Using MongoDB:		8.0.4
Using Mongosh:		2.2.5
mongosh 2.4.0 is available for download: https://www.mongodb.com/try/download/shell

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

test> show dbs   // 列出 MongoDB 实例中的所有数据库
admin   180.00 KiB
config   92.00 KiB
local    72.00 KiB
test> use admin   // 切换到 admin 数据库，也可以创建并使用其他数据库
switched to db admin
admin> db.createUser({   // 创建新用户
...   user: 'admin',     // 自定义用户名
...   pwd: '<强密码>',           // 自定义密码，应使用强密码
...   roles:[{
...     role: 'root',      // 授予超级管理员角色，可管理所有数据库
...     db: 'admin'        // 指定用户所在数据库
...   }]
... })
{ ok: 1 }
admin> quit   // 退出 MongoDB shell
```

可将以下文本直接复制至命令行：

```sql
db.createUser({
   user: 'admin',
   pwd: '<你的强密码>',
   roles:[{
     role: 'root',
     db: 'admin'
   }]
 })
```

创建用户后，启用密码验证：

编辑 **/usr/local/etc/mongodb.conf** 文件：

去掉 `#security:` 前的注释符号 `#`，随后在下一行加入 `authorization: enabled`，如下所示：

```ini
security:
  authorization: enabled   # 启用 MongoDB 用户认证和访问控制
```

重启 MongoDB 服务使配置生效：

```sh
# service mongod restart
```

## 登录方式

启用访问控制后，需使用用户名和密码登录，方式如下：

### 登录方式 ①

使用 `mongosh` 连接到本地 MongoDB 服务：

```sql
# mongosh mongodb://127.0.0.1:27017
Current Mongosh Log ID:	67bcb1bafa0080a2132d5665
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.5
Using MongoDB:		8.0.4
Using Mongosh:		2.2.5
mongosh 2.4.0 is available for download: https://www.mongodb.com/try/download/shell

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

test> use admin // 必须先切换到数据库 admin
switched to db admin
admin> db.auth('admin', '<你的密码>') // 使用用户名和密码登录 MongoDB 数据库
{ ok: 1 }
admin>
```

### 登录方式 ②

使用用户名 `admin` 和密码 `z` 登录 MongoDB：

```sql
# mongosh -u admin -p z
Current Mongosh Log ID:	67bcb200cbc3b601fb2d5665
Connecting to:		mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.5
Using MongoDB:		8.0.4
Using Mongosh:		2.2.5
mongosh 2.4.0 is available for download: https://www.mongodb.com/try/download/shell

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

test>
```

## 参考文献

* 阳'Blog. 宝塔面板使用 MongoDB 一些教程 PHP7\[EB/OL]. (2023-09-28)\[2026-03-25]. <https://yooer.me/%E5%AE%9D%E5%A1%94%E9%9D%A2%E6%9D%BF-%E4%BD%BF%E7%94%A8mongodb%E4%B8%80%E4%BA%9B%E6%95%99%E7%A8%8B-php7.html>. 详细介绍了 MongoDB 安装与基础配置，为本节提供实践参考。
* 吃饭@我. mongodb 添加管理员和用户\[EB/OL]. \[2026-03-25]. <https://chenyejun.github.io/blog/mongoDB/mongodbAddUser.html>. 系统讲解了 MongoDB 用户创建与角色划分，提供权限管理参考。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://book.bsdcn.org/di-33-zhang-shu-ju-ku-guan-li/di-33.5-jie-mongodb.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
