Swiftpack.co - mongodb/mongo-swift-driver as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by mongodb.
mongodb/mongo-swift-driver v1.2.0
The official MongoDB driver for Swift
⭐️ 277
🕓 4 weeks ago
macOS linux iOS
.package(url: "https://github.com/mongodb/mongo-swift-driver.git", from: "v1.2.0")



The official MongoDB driver for Swift applications on macOS and Linux.



The latest documentation for the driver is available here. The latest documentation for the driver's BSON library is available here.

Bugs / Feature Requests

Think you've found a bug? Want to see a new feature in mongo-swift-driver? Please open a case in our issue management tool, JIRA:

  1. Create an account and login: jira.mongodb.org
  2. Navigate to the SWIFT project: jira.mongodb.org/browse/SWIFT
  3. Click Create Issue - Please provide as much information as possible about the issue and how to reproduce it.

Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are public.

Security Concerns

Please see SECURITY.md for details on our security process.


The driver supports use with Swift 5.1+. The minimum macOS version required to build the driver is 10.14. The driver is tested in continuous integration against macOS 10.14, Ubuntu 16.04, and Ubuntu 18.04.

Installation is supported via Swift Package Manager.

You can find details about all our versions in this repo's releases page.

Step 1: Install Required System Libraries (Linux Only)

The driver vendors and wraps the MongoDB C driver (libmongoc), which depends on a number of external C libraries when built in Linux environments. As a result, these libraries must be installed on your system in order to build MongoSwift.

To install those libraries, please follow the instructions from libmongoc's documentation.

Step 2: Install the driver

The driver contains two modules to support a variety of use cases: an asynchronous API in MongoSwift, and a synchronous API in MongoSwiftSync. The modules share a number of core types such as options structs. The driver depends on our library swift-bson, containing a BSON implementation. All BSON symbols are re-exported from the drivers' modules, so you do not need to explicitly import BSON in your application.

To install the driver, add the package and relevant module as a dependency in your project's Package.swift file:

// swift-tools-version:5.1
import PackageDescription

let package = Package(
    name: "MyPackage",
    dependencies: [
        .package(url: "https://github.com/mongodb/mongo-swift-driver", .upToNextMajor(from: "1.1.0"))
    targets: [
        // Async module
        .target(name: "MyAsyncTarget", dependencies: ["MongoSwift"]),
        // Sync module
        .target(name: "MySyncTarget", dependencies: ["MongoSwiftSync"])

Then run swift build to download, compile, and link all your dependencies.

Example Usage

Note: You should call cleanupMongoSwift() exactly once at the end of your application to release all memory and other resources allocated by libmongoc.

Connect to MongoDB and Create a Collection


import MongoSwift
import NIO

let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4)
let client = try MongoClient("mongodb://localhost:27017", using: elg)

defer {
    // clean up driver resources
    try? client.syncClose()

    // shut down EventLoopGroup
    try? elg.syncShutdownGracefully()

let db = client.db("myDB")
let result = db.createCollection("myCollection").flatMap { collection in
    // use collection...


import MongoSwiftSync

defer {
    // free driver resources

let client = try MongoClient("mongodb://localhost:27017")

let db = client.db("myDB")
let collection = try db.createCollection("myCollection")

// use collection...

Note: we have included the client connectionString parameter for clarity, but if connecting to the default "mongodb://localhost:27017"it may be omitted.

Create and Insert a Document


let doc: BSONDocument = ["_id": 100, "a": 1, "b": 2, "c": 3]
collection.insertOne(doc).whenSuccess { result in
    print(result?.insertedID ?? "") // prints `.int64(100)`


let doc: BSONDocument = ["_id": 100, "a": 1, "b": 2, "c": 3]
let result = try collection.insertOne(doc)
print(result?.insertedID ?? "") // prints `.int64(100)`

Find Documents


let query: BSONDocument = ["a": 1]
// The `sort` option specifies the order in which results are returned
// via the cursor. In this case, `["_id": -1]` indicates that the documents will
// be returned in descending order according to the `_id` field.
let options = FindOptions(sort: ["_id": -1])
let result = collection.find(query, options: options).flatMap { cursor in
    cursor.forEach { doc in


let query: BSONDocument = ["a": 1]
// The `sort` option specifies the order in which results are returned
// via the cursor. In this case, `["_id": -1]` indicates that the documents will
// be returned in descending order according to the `_id` field.
let options = FindOptions(sort: ["_id": -1])
let documents = try collection.find(query, options: options)
for d in documents {
    print(try d.get())

Work With and Modify Documents

var doc: BSONDocument = ["a": 1, "b": 2, "c": 3]

print(doc) // prints `{"a" : 1, "b" : 2, "c" : 3}`
print(doc["a"] ?? "") // prints `.int64(1)`

// Set a new value
doc["d"] = 4
print(doc) // prints `{"a" : 1, "b" : 2, "c" : 3, "d" : 4}`

// Using functional methods like map, filter:
let evensDoc = doc.filter { elem in
    guard let value = elem.value.asInt() else {
        return false
    return value % 2 == 0
print(evensDoc) // prints `{ "b" : 2, "d" : 4 }`

let doubled = doc.map { elem -> Int in
    guard case let value = .int64(value) else {
        return 0

    return Int(value * 2)
print(doubled) // prints `[2, 4, 6, 8]`

Note that BSONDocument conforms to Collection, so useful methods from Sequence and Collection are all available. However, runtime guarantees are not yet met for many of these methods.

Usage With Kitura, Vapor, and Perfect

The Examples/ directory contains sample projects that use the driver with Kitura, Vapor, and Perfect.

Please note that the driver is built using SwiftNIO 2, and therefore is incompatible with frameworks built upon SwiftNIO 1. SwiftNIO 2 is used as of Vapor 4.0 and Kitura 2.5.

Development Instructions

See our development guide for instructions for building and testing the driver.


Stars: 277
Last commit: Yesterday
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.


Release Notes

4 weeks ago

We are pleased to announce the 1.2.0 release of the Swift driver.

This release most notably adds support for the following features:

MongoDB Versioned API

MongoDB 5.0 introduced supported for the versioned API, which will make it much easier for users to upgrade their server versions without experiencing backward-breaking changes.

To specify an API version for your application, provide a version via MongoClientOptions (currently, the only supported API version is 1):

let opts = MongoClientOptions(
    serverAPI: MongoServerAPI(version: .v1)

// Create an async client
let client = try MongoClient("mongodb://localhost:27017", using: myEventLoopGroup, options: opts)

// Or, create a sync client
let client = try MongoClient("mongodb://localhost:27017", options: opts)

Serverless MongoDB Support / Load Balancer Support

This release adds support for using the driver with Serverless MongoDB, which is currently in preview.

This is enabled via new support for connecting to a MongoDB cluster behind a TCP load balancer, which is supported via the loadBalanced connection string option or by setting the loadBalanced property on MongoClientOptions.

MongoDB 5.0 Support

This release adds full support for using new MongoDB 5.0 features, including creating and working with time series collections as well as extended support for the “snapshot” read concern; see the MongoDB 5.0 release notes for more details.

OCSP Support

The driver previously had implicit support for the Online Certificate Status Protocol (OCSP) via the underlying C driver, however as part of this release we have added explicit testing for this from Swift along with support for configuring it programmatically via MongoClientOptions, using the tlsDisableCertificateRevocationCheck and tlsDisableOCSPEndpointCheck options.

Please see our TLS Guide for more information.

Below are a selected list of tickets with user-facing implications; for a full list of completed tickets see this Jira query.

Included Tickets


  • SWIFT-1322 - listCollections does not respect batchSize option
  • SWIFT-1347 - ClientSession.pinnedServerAddress leaks memory (in tests only)

New Feature

  • SWIFT-787 - OCSP Support
  • SWIFT-1025 - Versioned MongoDB API for Drivers
  • SWIFT-1094 - Load Balancer Support
  • SWIFT-797 - Allow hinting the delete command
  • SWIFT-801 - support ability to pass hint to update
  • SWIFT-788 - Allow passing hint to findAndModify update and replace operations
  • SWIFT-904 - Add connectTimeoutMS option to MongoClientOptions
  • SWIFT-1157 - Implement ExpressibleByXLiteral for IndexHint
  • SWIFT-1102 - Snapshot reads on Secondaries
  • SWIFT-560 - Add the ability to specify a pipeline to an update command
  • SWIFT-1108 - Time-series Collections
  • SWIFT-1225 - Support ‘let’ option for aggregate command
  • SWIFT-1100 - Support truncatedArrays field in ChangeStream update descriptions
  • SWIFT-1307 - Expose serviceId in command monitoring events


  • SWIFT-910 - Lift restriction on authSource without credentials
  • SWIFT-1099 - Change estimatedDocumentCount() to use the $collStats Agg Stage Instead of Count Command
  • SWIFT-1107 - Mitigate pain of using field names with dots and dollars
  • SWIFT-1211 - Use “hello” command for monitoring if supported
  • SWIFT-1173 - Use “hello” command when API version is declared


  • SWIFT-1256 - Vendor libmongoc 1.19.0
  • SWIFT-1363 - Vendor libmongoc 1.19.1
  • SWIFT-1409 - Vendor libmongoc 1.19.2
  • SWIFT-1224 - Increase maxWireVersion for MongoDB 5.0


Thanks to everyone who contributed to this release!

  • @agolin95
  • @bynn
  • @isabelatkinson
  • @kmahar
  • @patrickfreed

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics