对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

MongoDB Swift 驱动程序

欢迎访问官方 MongoDB Swift 驱动程序文档站点。您可以将驱动程序添加到您的应用程序中,以便在 Swift 中使用 MongoDB。使用 Swift Package Manager 进行下载,或使用我们的使用指南中的示例来设置一个可运行的项目。

重要

从 2022 年起,Swift 驱动程序不再处于积极开发状态。

请参阅安装

要连接到 MongoDB Atlas 集群,请使用集群的 Atlas 连接字符串:

import MongoSwiftSync
defer {
// free driver resources
cleanupMongoSwift()
}
// replace the following string with your connection uri
let uri = "mongodb+srv://<db_username>:<db_password>@<cluster-address>/test?w=majority"
let client = try MongoClient(uri)
// print a list of database names
print (try client.listDatabaseNames())
// your application logic
import MongoSwift
import NIO
let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4)
// replace the following string with your connection uri
let uri = "mongodb+srv://<db_username>:<db_password>@<cluster-address>/test?w=majority"
let client = try MongoClient(
uri,
using: elg
)
defer {
// clean up driver resources
try? client.syncClose()
cleanupMongoSwift()
// shut down EventLoopGroup
try? elg.syncShutdownGracefully()
}
// print a list of database names
print(try client.listDatabaseNames().wait())
// your application logic

如果您需在本地机器上运行 MongoDB 服务器以用于开发目的而不是使用 Atlas 集群,则需完成以下操作:

  1. 下载 MongoDB Server Community 或 Enterprise 版本。

  2. 安装并配置 MongoDB Server。

  3. 启动该服务器。

重要

务必保护您的 MongoDB 服务器免受恶意攻击。请参阅我们的安全检查清单,获取安全建议清单。

在成功启动 MongoDB 服务器后,在驱动程序连接代码中指定连接字符串。

如果 MongoDB Server 在本地运行,您可以使用连接字符串 "mongodb://localhost:<port>",其中 <port> 是您配置服务器以侦听传入连接的端口号。

如果您需要指定其他主机名或 IP 地址,请参阅我们的服务器手册中关于连接字符串的条目。

要测试是否能够连接到服务器,请替换连接到 MongoDB Atlas 示例代码中的连接字符串,并运行此代码。

本部分的兼容性表指定了与特定版本的 MongoDB 一起使用的 MongoDB Swift 驱动程序的推荐版本。

第一列列出驱动程序版本。

重要

在服务器版本生命周期结束 (EOL) 日期之后的三年内,MongoDB 确保 MongoDB Server 与驱动程序兼容。要了解有关 MongoDB 版本和 EOL 日期的更多信息,请参阅 MongoDB 软件生命周期时间表。

Icon
解释

✓

支持所有功能。

⊛

该驱动程序版本将与 MongoDB 版本一起使用,但并不支持所有新的 MongoDB 功能。

✗

该驱动程序版本不适用于 MongoDB 版本。尝试连接到 MongoDB 版本将会导致错误。

无标记

驱动程序版本未使用 MongoDB 版本测试。

Swift 驱动程序版本
MongoDB 7.0
MongoDB 6.0
MongoDB 5.0
MongoDB 4.4
MongoDB 4.2
MongoDB 4.0
MongoDB 3.6

1.3.0[1]

⊛

✓

✓

✓

✓

✓

1.2.0 [1]

⊛

✓

✓

✓

✓

✓

1.1.0 [2]

⊛

⊛

✓

✓

✓

✓

1.0.0 [2]

⊛

⊛

✓

✓

✓

✓

因为 Swift 驱动程序尚未开发,所以尚未在 MongoDB Server 7.0 或更高版本上进行测试。

Swift 驱动程序与 3.6 之前的 MongoDB 服务器版本不兼容。

[1](1, 2) 版本 1.2 和 1.3 不支持客户端字段级加密、GridFS 以及使用 AWS IAM 角色进行身份验证。

[2](1、2)版本 1.0 和 1.1 不支持 OCSP、客户端字段级加密、GridFS 以及使用 AWS IAM 角色进行身份验证。

MongoDB Swift 驱动程序需要 Swift 5.1 或更高版本。