1. 简介

MongoDB 是一款流行的 NoSQL 数据库,具备高扩展性、高性能、高可用性以及对实时数据处理的支持。

本文将介绍 MongoDB Atlas——MongoDB 官方提供的全托管数据库服务(Database as a Service),支持多云部署(AWS、GCP 和 Azure)。

2. 什么是 MongoDB Atlas?

MongoDB Atlas 是基于云的数据库服务,负责处理 MongoDB 数据库的部署、监控、安全和扩展。

该服务有效隐藏了数据库基础设施管理的复杂性,支持通过多种方式与现代 Web/移动应用集成:

  • MongoDB Shell
  • 语言特定的 MongoDB 驱动程序
  • MongoDB Atlas API

3. MongoDB Atlas 界面操作

通过 MongoDB Atlas 官网 的直观界面,我们来创建第一个集群。

3.1. 创建账户

首先注册并创建账户: MongoDB 注册界面

登录后,可在仪表盘访问部署、服务和安全设置。

3.2. 创建集群

点击仪表盘的 Create 按钮创建集群: 创建集群

创建时 Atlas 界面允许根据需求选择服务器类型(如 M10、M5、M0),并提供云服务商、区域和安全配置选项: 部署集群

集群 BaeldungCluster 创建部署后,可查看详情并选择:

  • 添加数据
  • 迁移数据
  • 加载示例数据(生成 sample_mflix 数据库) 集群概览

右侧工具栏提供开发者常用功能。加载示例数据后,仪表盘会显示最近 6 小时的关键指标:

  • 读写操作数
  • 逻辑存储大小
  • 连接数 集群仪表盘

通过集合列表可可视化查看数据: 集群集合

注意sample_mflix 数据库包含 commentsmoviestheatres 等集合,界面支持查找、插入和聚合文档操作。

3.3. 连接集群

创建数据库用户以连接 BaeldungCluster(支持 Shell 或应用驱动): 添加数据库用户

用户创建后,在 Database Access 界面查看配置: 数据库访问详情

点击仪表盘的 Connect 按钮,选择连接方式:

使用 MongoDB Shell 的连接步骤: 通过 Shell 连接

获取 Java 应用连接字符串(选择 Java 驱动): Java 连接配置

其他连接方式(如 Compass、Atlas SQL)可按需探索。

3.4. 查询数据

Atlas 界面支持通过 Atlas Search 查询数据,提供:

  • Atlas Vector Search
  • 自动补全
  • 丰富查询 DSL 集群搜索

创建搜索索引步骤:

  1. 选择 Visual Editor 创建搜索索引
  2. 命名索引(如 baeldungindex)并选择 sample_mflix 数据库 索引名称和数据源
  3. 调整默认索引配置 索引配置

索引就绪后,通过 Search Tester 进行通配符搜索: 搜索测试器

4. 使用 MongoDB Shell 执行基础操作

通过 MongoDB Shell 连接集群并执行命令。

4.1. 连接集群

按上述说明安装 Shell 后,连接 BaeldungCluster

mongosh "mongodb+srv://baeldungcluster.oyixi.mongodb.net/" --apiVersion 1 --username baeldungadmin

输入用户 baeldungadmin 的密码后,Shell 显示连接详情:

Enter password: ********************
Current Mongosh Log ID:    66cb11d7d082639cbff99270
Connecting to:        mongodb+srv://<credentials>@baeldungcluster.oyixi.mongodb.net/?appName=mongosh+2.2.15
Using MongoDB:        7.0.12 (API Version 1)
Using Mongosh:        2.2.15
mongosh 2.3.0 is available for download: https://www.mongodb.com/try/download/shell

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

Atlas atlas-2e83ir-shard-0 [primary] test> 

4.2. 查找文档

切换到 sample_mflix 数据库:

use sample_mflix;

查看所有集合:

show collections;

查询 comments 集合的所有文档:

db.comments.find();

输出结果(已格式化为 JSON):

[{
    _id: ObjectId('5a9427648b0beebeb69581b9'),
    name: 'Sandor Clegane',
    email: 'sandor@example.com',
    movie_id: ObjectId('573a1392f29313caabcdbceb'),
    text: 'Totam facilis ad amet a sunt aut quia.',
    date: ISODate('2010-01-11T08:07:56.000Z')
  },
  {
    _id: ObjectId('5a9427648b0beebeb69581cf'),
    name: 'Catelyn Stark',
    email: 'catelyn@example.com',
    movie_id: ObjectId('573a1392f29313caabcdbd59'),
    text: 'Explicabo voluptatum soluta sed optio ea.',
    date: ISODate('1983-12-23T05:39:52.000Z')
  },
...
]

4.3. 添加文档

comments 集合插入文档:

db.comments.insertOne({
  "name": "Anshul Bansal",
  "movie": "Matrix",
  "text": "nice sci-fi movie"
})

返回确认信息(含自动生成的 ObjectId):

{
  acknowledged: true,
  insertedId: ObjectId('66cb372ad082639cbff99271')
}

4.4. 使用搜索索引

通过 baeldungindex 搜索集合:

db.comments.aggregate([
  {
    $search: {
      index: "baeldungindex",
      text: {
        query: "Anshul Bansal",
        path: {
          wildcard: "*"
        }
      }
    }
  }
])

输出结果(ObjectId 与上一步新增文档一致):

[
  {
    _id: ObjectId('66cb372ad082639cbff99271'),
    name: 'Anshul Bansal',
    movie: 'Matrix',
    text: 'nice sci-fi movie'
  }
]

5. MongoDB Atlas CLI

Atlas 提供 专用命令行工具,通过直观命令管理数据库服务。

5.1. 安装

安装 Atlas CLI:

brew install mongodb-atlas

验证安装:

atlas --version
# 输出示例:1.26.0

5.2. 登录

执行登录:

atlas auth login

浏览器打开登录页,输入一次性验证码:

To verify your account, copy your one-time verification code:
7QGP-TQXH

Paste the code in the browser when prompted to activate your Atlas CLI. Your code will expire after 10 minutes.

To continue, go to https://account.mongodb.com/account/connect

5.3. 列出项目、用户和集群

查看项目列表:

atlas projects list
# 输出示例:
ID                         NAME
66b9bcede5fc6d307bbc8e48   Baeldung

查看数据库用户:

atlas dbusers list
# 输出示例:
USERNAME DATABASE
baeldungadmin admin

查看集群:

atlas clusters list
# 输出示例:
ID NAME MDB VER STATE
66ca41392ed10b3dd115e87f BaeldungCluster 7.0.12 IDLE

5.4. 创建集群

通过 CLI 创建集群:

atlas clusters create baeldungatlascluster --provider AWS --region EU_CENTRAL_1

6. MongoDB Atlas API

Atlas 提供 程序化 API 管理部署、集群和数据。

6.1. 创建 API 密钥

在界面创建 API 密钥(需配置权限): 创建 API 密钥

⚠️ 重要:私钥仅显示一次,请妥善保存。公钥可在 Organization Access Manager 查看: 组织访问管理

6.2. 列出组

获取所有组(项目):

curl --user "<publickey>:<privatekey>" --digest \
  --header "Content-Type: application/json" \
  --header "Accept: application/vnd.atlas.2023-02-01+json" \
  --request GET "https://cloud.mongodb.com/api/atlas/v2/groups?pretty=true"

响应示例:

{
  "links": [...],
  "results": [
    {
      "clusterCount": 1,
      "created": "2024-08-12T07:42:46Z",
      "id": "66b9bcede5fc6d307bbc8e48",
      "name": "Baeldung",
      "orgId": "66b9bcede5fc6d307bbc8dc5",
      "tags": []
    }
  ],
  "totalCount": 1
}

6.3. 列出集群

获取指定组下的集群:

curl --user "<publickey>:<privatekey>" --digest \
  --header "Content-Type: application/json" \
  --header "Accept: application/vnd.atlas.2023-02-01+json" \
  --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/66b9bcede5fc6d307bbc8e48/clusters?pretty=true"

响应包含集群详情(连接字符串、ID、副本集配置等):

{
  "results": [
    {
      "backupEnabled": false,
      "clusterType": "REPLICASET",
      "connectionStrings": {
        "standard": "mongodb://baeldungcluster-shard-00-00.oyixi.mongodb.net:27017,...",
        "standardSrv": "mongodb+srv://baeldungcluster.oyixi.mongodb.net"
      },
      "id": "66ca41392ed10b3dd115e87f",
      "name": "BaeldungCluster",
      "replicationSpecs": [...],
      "stateName": "IDLE"
    }
  ]
}

6.4. 列出索引

获取集群的搜索索引:

curl --user "<publickey>:<privatekey>" --digest \
  --header "Content-Type: application/vnd.atlas.2024-05-30+json" \
  --header "Accept: application/vnd.atlas.2024-05-30+json" \
  --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/66b9bcede5fc6d307bbc8e48/clusters/BaeldungCluster/search/indexes?pretty=true"

响应包含 baeldungindex 的状态和配置:

[ {
  "collectionName" : "comments",
  "database" : "sample_mflix",
  "name" : "baeldungindex",
  "status" : "READY",
  "statusDetail" : [ {
    "hostname" : "atlas-2e83ir-shard-00-00",
    "status" : "READY"
  } ]
} ]

7. 总结

本文介绍了 MongoDB Atlas——MongoDB 的云托管服务

核心内容覆盖

  1. 通过界面创建、部署和访问集群
  2. 使用 MongoDB Shell 执行基础操作
  3. 通过 Atlas CLI 和 API 管理数据库服务

Atlas 简化了数据库运维,让开发者更专注于业务逻辑实现。对于需要快速搭建生产级 MongoDB 环境的场景,Atlas 是个简单粗暴的选择。


原始标题:Intro to MongoDB Atlas | Baeldung