The official MongoDB driver for Swift

Overview

sswg:incubating|104x20

MongoSwift

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

Index

Documentation

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.

Installation

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",
    platforms: [
        .macOS(.v10_14) // minimum macOS version driver supports
    ],
    dependencies: [
        .package(url: "https://github.com/mongodb/mongo-swift-driver", .upToNextMajor(from: "1.3.0-alpha.2"))
    ],
    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

Async/Await (recommended):

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()
    cleanupMongoSwift()

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

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

Async (EventLoopFutures):

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()
    cleanupMongoSwift()

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

let db = client.db("myDB")

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

Sync:

import MongoSwiftSync

defer {
    // free driver resources
    cleanupMongoSwift()
}

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

Async/Await (recommended):

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

Async (EventLoopFutures):

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

Sync:

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

Async/Await (recommended):

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])
for try await doc in try await collection.find(query, options: options) {
    print(doc)
}

Async (EventLoopFutures):

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
        print(doc)
    }
}

Sync:

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 web application projects that use the driver with Kitura, Vapor, and Perfect. We also have an example full-stack Swift app with an iOS frontend and a backend built with Vapor.

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.

Comments
  • [Memory leak] bson_malloc / swift_slowAlloc

    [Memory leak] bson_malloc / swift_slowAlloc

    Apologies for only reporting memory leaks 🤷🏻‍♂️

    I am not sure whether these two are related or not.

    Environment:

    • macOS Catalina 10.15.5
    • MongoDB 4.2.7 Community (official docker container)
    • Mongo driver 1.0.0
    • Apple Swift version 5.2.4 (swiftlang-1103.0.32.9 clang-1103.0.32.53) / Target: x86_64-apple-darwin19.5.0
    • Compiled in "RELEASE" mode

    Unfortunately, I am not sure how to reproduce it.

    Screenshot 2020-07-27 at 14 47 10

    Screenshot 2020-07-27 at 14 48 08

    Update 31st July 2020

    Not Fixed

    Screenshot 2020-07-31 at 11 11 44

    Screenshot 2020-07-31 at 11 11 54

    Fixed by https://github.com/mongodb/mongo-swift-driver/issues/516#issuecomment-666863404

    Screenshot 2020-07-29 at 10 36 56

    Screenshot 2020-07-29 at 10 37 12

    Screenshot 2020-07-29 at 10 37 28

    Screenshot 2020-07-29 at 10 37 47

    Screenshot 2020-07-29 at 10 38 00

    tracked-in-jira 
    opened by valeriomazzeo 30
  • CLibMongoC compilation fails when SPM package used in an Xcode project

    CLibMongoC compilation fails when SPM package used in an Xcode project

    Information

    Swift version

    $ swift --version
    Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15)
    Target: x86_64-apple-darwin19.2.0
    
    

    Operating system

    $ uname -a
    Darwin sleeperservice.local 19.2.0 Darwin Kernel Version 19.2.0: Sat Nov  9 03:47:04 PST 2019; root:xnu-6153.61.1~20/RELEASE_X86_64 x86_64
    

    Driver version

    $ cat MongoTest.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
    {
      "object": {
        "pins": [
          {
            "package": "MongoSwift",
            "repositoryURL": "https://github.com/mongodb/mongo-swift-driver.git",
            "state": {
              "branch": "master",
              "revision": "8cc72888b860828a12bddd66beac99b693a8481a",
              "version": null
            }
          },
          {
            "package": "Nimble",
            "repositoryURL": "https://github.com/Quick/Nimble.git",
            "state": {
              "branch": null,
              "revision": "f8657642dfdec9973efc79cc68bcef43a653a2bc",
              "version": "8.0.2"
            }
          },
          {
            "package": "swift-nio",
            "repositoryURL": "https://github.com/apple/swift-nio",
            "state": {
              "branch": null,
              "revision": "f6487a11d80bfb9a0a0a752b7442847c7e3a8253",
              "version": "2.12.0"
            }
          }
        ]
      },
      "version": 1
    }
    
    

    What is the version(s) of mongod that you are running with the driver?

    $ mongod --version
    db version v4.2.1
    git version: edf6d45851c0b9ee15548f0f847df141764a317e
    allocator: system
    modules: none
    build environment:
        distarch: x86_64
        target_arch: x86_64
    

    What is your server topology?

    A single MongoDB instance running locally.

    How did you install libmongoc and libbson on your system

    Installed/managed by the SPM package.

    Version of libmongoc and libbson

    N/A

    What is the problem?

    When adding the MongoSwift SPM packge to Xcode, MongoSwift compilation fails because Xcode is unable to build the CLibMongoC Objective-C module due to the following erros:

    • Only <bson/bson.h> can be included directly
    • Only <mongoc/mongoc.h> can be included directly

    These errors are outputted for every Swift file in MongoSwift.

    Cloning MongoSwift at the same version and building separately from an Xcode project with swift build works as expected. Cloning MongoSwift, generating an Xcode project (with make project), and adding that project to an Xcode Workspace also compiles successfully as expected. Only when included as an SPM package through Xcode's integration is CLibMongoC broken.

    Reproducing the bug

    1. Create a new macOS app project in Xcode.
    2. In the app target, under "Frameworks, Libraries, and Embedded Content", click the + button.
    3. Click Add Other -> Add Package Depedency...
    4. Enter https://github.com/mongodb/mongo-swift-driver and click Next
    5. Choose the specific commit 8cc72888b860828a12bddd66beac99b693a8481a as the package version.
    6. Ensure the checkbox next to the MongoSwift library is checked.
    7. Attempt to compile the app.
    8. Observe that CLibMongoC compilation fails.
    opened by shadowfacts 16
  • SWIFT-1051 ⁃ [MemoryLeak] [Linux] Massive memory consumption on encoding

    SWIFT-1051 ⁃ [MemoryLeak] [Linux] Massive memory consumption on encoding

    Information

    I see this issue only if I use this driver on linux in docker container. And I don't think this is issue of a container or my code, will provide more evidence below

    I believe this driver is designed to be used on server, which mean it most likely will be used in swift container.

    Swift version

    I'm using docker container swift:bionic-5.3.2, and also checked slim version.

    Driver version

    swift driver: 1.0.1 mongo-c-driver: 1.16

    What is the problem?

    This lines are leaking

    let decoder = BSONDecoder()
    decoder.dateDecodingStrategy = .bsonDateTime
    return try decoder.decode(SomeCodable.self, from: BSONDocument)
    

    I attached sample code as zip: EmptyVaporImageToZip.zip

    this is small project, which only do Decoding. I don't do 200k codings in a row usually, this is just for test purpose. This is how I'm using it: I'm getting BSONDocument from collection and using BSONDecoder to decode into my objects. Looks like proper usage. Let me know if I'm doing it wrong.

    If you run it in container - you will get massive memory usage - 467MB. Info I'm getting using docker stats Alternatively there is native encoding - which use only 2MB to encode the same amount of objects. As result service which uses this driver restart really often and the more API calls I have, the more ofter service restarts.

    This difference in footprint lead me to idea that this is issue of a driver rather than my code. Easy switch can be done in main.swift line 11 or 12. Comment/uncomment one of them

    Reproducing the bug

    Build on macOS to see that there is no so big issue

    1. Open zip
    2. Generate project with swift package generate-xcodeproj
    3. Run app. You will see that memory jumps, which is fine. Cos native one doing things close to it.

    Reproduce issue in linux container:

    1. You need build container with docker build --no-cache -t empty-service-image-build -f ./AnalyticsServiceBuildImage.dockerfile ./ . You can see that container is basic - install mongo driver and build swift app on top
    2. Run container using docker run empty-service-image-build
    3. Run docker stats to see mem usage. With BSONEncoder you see huge memory footprint(400+MB). You can switch to native decoding and see desired foot print (~2MB)
    opened by NikolayJuly 14
  • Error while loading shared libraries: libmongoc-1.0.so.0: cannot open shared object file: No such file or directory

    Error while loading shared libraries: libmongoc-1.0.so.0: cannot open shared object file: No such file or directory

    Swift version

    Swift version 5.1.2 (swift-5.1.2-RELEASE)
    Target: x86_64-unknown-linux-gnu
    
    

    Operating system

    What does this command give you?

    #79-Ubuntu SMP Tue Nov 12 10:36:11 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
    
    

    Driver version

    What does this command give you?

    {
            "package": "MongoSwift",
            "repositoryURL": "https://github.com/mongodb/mongo-swift-driver",
            "state": {
              "branch": null,
              "revision": "dd26fc7e4dda121626c64e0205fba75bd435db23",
              "version": "0.1.3"
            }
    
    

    What is the version(s) of mongod that you are running with the driver?

    Try running:

    db version v4.2.1
    git version: edf6d45851c0b9ee15548f0f847df141764a317e
    OpenSSL version: OpenSSL 1.1.1  11 Sep 2018
    allocator: tcmalloc
    modules: none
    
    
    
    
    ### How did you install `libmongoc` and `libbson` on your system
    
    built from GIT as per http://mongoc.org/libmongoc/1.14.0/installing.html
    
    
    ### Version of `libmongoc` and `libbson`
    
    What does this command give you?
    
    pkg-config --modversion libbson-1.0
    1.15.2
    
    
    

    What is the problem?

    cannot compile

    Reproducing the bug

    swift run

    
    home/gurugeek/tennispress/.build/checkouts/mongo-swift-driver/Sources/MongoSwift/Operations/CountOperation.swift:73:21: warning: 'mongoc_collection_count_with_opts' is deprecated
            let count = mongoc_collection_count_with_opts(
                        ^
    /home/gurugeek/tennispress/.build/checkouts/mongo-swift-driver/Sources/MongoSwift/Operations/CountOperation.swift:73:21: warning: 'mongoc_collection_count_with_opts' is deprecated
            let count = mongoc_collection_count_with_opts(
                        ^
    /home/gurugeek/tennispress/.build/checkouts/mongo-swift-driver/Sources/MongoSwift/Operations/CountOperation.swift:73:21: warning: 'mongoc_collection_count_with_opts' is deprecated
            let count = mongoc_collection_count_with_opts(
                        ^
    /home/gurugeek/tennispress/.build/checkouts/mongo-swift-driver/Sources/MongoSwift/Operations/CountOperation.swift:73:21: warning: 'mongoc_collection_count_with_opts' is deprecated
            let count = mongoc_collection_count_with_opts(
                        ^
    /home/gurugeek/tennispress/.build/checkouts/mongo-swift-driver/Sources/MongoSwift/Operations/CountOperation.swift:73:21: warning: 'mongoc_collection_count_with_opts' is deprecated
            let count = mongoc_collection_count_with_opts(
                        ^
    /home/gurugeek/tennispress/.build/checkouts/Stencil/Sources/Template.swift:11:3: warning: 'internal(set)' modifier is redundant for an internal property
      internal(set) var environment: Environment
      ^~~~~~~~~~~~~~
      
    /home/gurugeek/tennispress/.build/checkouts/Stencil/Sources/Template.swift:11:3: warning: 'internal(set)' modifier is redundant for an internal property
      internal(set) var environment: Environment
      ^~~~~~~~~~~~~~
      
    [335/335] Linking tennispress
    .build/x86_64-unknown-linux/debug/tennispress: error while loading shared libraries: libmongoc-1.0.so.0: cannot open shared object file: No such file or directory
    
    
    opened by gurugeek 13
  • accessing mongodb with authentication

    accessing mongodb with authentication

    I don't know if this Has been asked or not, but I can't found it so here I want to ask about it.

    I can create and access the mongoDB which I have created on a cloud server. If I start it without

    --auth

    options, I can access it perfectly, but I want to start with authentication options. How do I put the username and password to mongoswift?

    opened by darwinharianto 13
  • SWIFT-193: Proof-of-concept for various approaches

    SWIFT-193: Proof-of-concept for various approaches

    SWIFT-193

    deep breath

    This PR details nearly 5 (one is a combination of others) approaches for improving BSON usability in the driver. These are sorted in order of least to most promising (1 < 2 < 3 == 4 <? 5):

    1. BSONValue?? - Using a double optional so as to distinguish between nil and Optional(nil), where the former suggests a missing value and the latter suggests a true null value in the BSON.
    2. BSONMissing - Using a dedicated object for representing a missing value/non-existent key. This is (somewhat) akin to something like undefined for Javascript.
    3. BSONNull - Similar to BSONMissing, but instead of providing a dedicated object for representing a missing value/non-existent key, we provide one for the BSON null value.
    4. NSNull - Analogous to BSONNull, but uses the familiar (to Objective-C folks, at least) NSNull. This is what MongoKitten does.
    5. BSONMissing && (BSONNull || NSNull) - A combination of 2 && (3 || 4) that provides a guarantee of BSONValue return from any BSON. In other words, since we would no longer require the use of nil as a return from retrieving values from the document, there is no reason to use BSONValue? and unwraps.

    All of these approaches aim to remove the ambiguity of nil in our current BSON usability. This is the immediate improvement, but this improves experience of dealing with Document and BSONValue and [BSONValue] in general.

    This PR holds all the approaches mentioned above in a single branch, meaning implementations co-exist, in some sense. Currently, the code is set to use one approach, with other approach-specific logic commented out nearby. However, the semantics/code for how an end-user may use each of the approaches is kept in a test case meant to be a demo area (in BSONValueTests.swift). This means however that some of the demo usage code is not actually correct, since the approach-specific logic may be commented out. This is fine, since the test case code is just meant to show how the end-user experience would look like.

    Approach 1 is shown via a Swift dictionary holding BSONValue?? since the semantics should be similar. @kmahar may be able to go further into depth with this, as this was a great suggestion from her.

    Approach 5 seems very promising in removing BSONValue? hassles, but couldn't be included in part of this PR since it can't co-exist with the other approaches so it includes a question mark in its ranking. I am totally open to making a new PoC branch that branches off this one that tries showcasing the possibility of removing BSONValue? via approach 5. Its downside is that we break from using nil and Swift dictionary style.

    The 'demos' were made with the goal of showing how an end-user would do the following things:

    1. Getting an existing key out of the dictionary
    2. Checking for key existence
    3. Checking to see if the returned value implies a true nil or missing.
    4. Getting the value of a key for which the value is null.

    Finally, this is a proof-of-concept branch that should not be merged. This exists solely to get the team some visual examples on how the approaches would work, look and feel like. Once we choose an approach, a true SWIFT-193 branch will be used with the chosen approach and put up as a 'true' PR. This PR will not be merged and therefore, I imagine it needs no reviewers.

    With my ramblings, notes and disclaimers out of the way, let me know about your thoughts, use-cases/scenarios I should add, and so on!!! (Sorry for the many words)

    opened by Utagai 13
  • Linux support

    Linux support

    It seems that this does not work well on linux.

    My swift is:

    Swift version 4.0.2 (swift-4.0.2-RELEASE)
    Target: x86_64-unknown-linux-gnu.
    

    I got the following build errors.

    It seems that a label rawValue is needed.

    /data/git/mongo-swift-driver/Sources/MongoSwift/APM.swift:470:51: error: missing argument label 'rawValue:' in call
        static let commandStarted = Notification.Name("commandStarted")
                                                      ^
                                                      rawValue: 
    

    We need LinuxMain.swift for tests.

    error: missingLinuxMain
    

    This is not the linux issue. swift 4.0.2 needs to implement the == func for Equatable class. Now, IBM Z supports swift (https://www.ibm.com/developerworks/downloads/r/toolkitforswift/), but it does not have swift 4.1.0.

    /data/git/mongo-swift-driver/Tests/MongoSwiftTests/CodecTests.swift:63:12: error: type 'CodecTests.BasicStruct' does not conform to protocol 'Equatable'
        struct BasicStruct: Decodable, Equatable {
               ^
    

    Similarly, swift 4.0.2 does not support compactMap.

    /data/git/mongo-swift-driver/Sources/MongoSwift/BSON/BsonDecoder.swift:193:31: error: value of type '[String]' has no member 'compactMap'
            return self.container.keys.compactMap { Key(stringValue: $0) }
                   ~~~~~~~~~~~~~~~^~~~ ~~~~~~~~~~
    

    I fixed the above issues locally and succeeded to build mongo-swift-driver. But, I got a segmentation fault in a test as follows.

    Test Suite 'All tests' started at 2018-05-16 06:33:19.615
    Test Suite 'debug.xctest' started at 2018-05-16 06:33:19.616
    Test Suite 'ClientTests' started at 2018-05-16 06:33:19.616
    Test Case 'ClientTests.testListDatabases' started at 2018-05-16 06:33:19.616
    Segmentation fault
    

    Perhaps, this is not tested on linux. If so, I hope to test mongo-swift-driver on linux. And if possible, I hope to test with a little prior version of swift.

    opened by tnakaike 12
  • SWIFT-198: Use setValue where possible rather than subscript setter

    SWIFT-198: Use setValue where possible rather than subscript setter

    SWIFT-198

    This PR replaces instances where we use subscript-setting in a throwing function with setValue(). This should help avoid preconditionFailure's and instead propagate a non-fatal error for the end-user.

    There were some instances of functions that were declared as rethrows. From my understanding, these functions only throw if their argument which is a function/closure throws itself, so we cannot use setValue() without marking those function as throws. This was enough of a change that I figured it shouldn't be included in this ticket. Plus, these were implemented in conformance to Sequence, and I believe marking them as throws would break the conformance.

    As usual with these kinds of PRs, let me know if you think I have missed any instances.

    opened by Utagai 11
  • WARNING: mongoc: Unknown rpc type: 0x00000000

    WARNING: mongoc: Unknown rpc type: 0x00000000

    Information

    Running Vapor Server Side Swift (latest) with (latest) mongo-swift-driver

    Swift version

    Apple Swift version 5.1.2 (swiftlang-1100.0.278 clang-1100.0.33.9)
    Target: x86_64-apple-darwin18.7.0
    

    Operating system

    Darwin local.local 18.7.0 Darwin Kernel Version 18.7.0: Sat Oct 12 00:02:19 PDT 2019; root:xnu-4903.278.12~1/RELEASE_X86_64 x86_64 i386 MacBookPro11,5 Darwin
    

    Driver version

    {
      "object": {
        "pins": [
          {
            "package": "Console",
            "repositoryURL": "https://github.com/vapor/console.git",
            "state": {
              "branch": null,
              "revision": "74cfbea629d4aac34a97cead2447a6870af1950b",
              "version": "3.1.1"
            }
          },
          {
            "package": "Core",
            "repositoryURL": "https://github.com/vapor/core.git",
            "state": {
              "branch": null,
              "revision": "18f2436bf7a6bc2224372c0885db2e0159af1649",
              "version": "3.9.2"
            }
          },
          {
            "package": "Crypto",
            "repositoryURL": "https://github.com/vapor/crypto.git",
            "state": {
              "branch": null,
              "revision": "df8eb7d8ae51787b3a0628aa3975e67666da936c",
              "version": "3.3.3"
            }
          },
          {
            "package": "CwlCatchException",
            "repositoryURL": "https://github.com/mattgallagher/CwlCatchException.git",
            "state": {
              "branch": null,
              "revision": "7cd2f8cacc4d22f21bc0b2309c3b18acf7957b66",
              "version": "1.2.0"
            }
          },
          {
            "package": "CwlPreconditionTesting",
            "repositoryURL": "https://github.com/mattgallagher/CwlPreconditionTesting.git",
            "state": {
              "branch": null,
              "revision": "c228db5d2ad1b01ebc84435e823e6cca4e3db98b",
              "version": "1.2.0"
            }
          },
          {
            "package": "DatabaseKit",
            "repositoryURL": "https://github.com/vapor/database-kit.git",
            "state": {
              "branch": null,
              "revision": "8f352c8e66dab301ab9bfef912a01ce1361ba1e4",
              "version": "1.3.3"
            }
          },
          {
            "package": "Fluent",
            "repositoryURL": "https://github.com/vapor/fluent.git",
            "state": {
              "branch": null,
              "revision": "783819d8838d15e1a05b459aa0fd1bde1e37ac26",
              "version": "3.2.1"
            }
          },
          {
            "package": "FluentSQLite",
            "repositoryURL": "https://github.com/vapor/fluent-sqlite.git",
            "state": {
              "branch": null,
              "revision": "c32f5bda84bf4ea691d19afe183d40044f579e11",
              "version": "3.0.0"
            }
          },
          {
            "package": "HTTP",
            "repositoryURL": "https://github.com/vapor/http.git",
            "state": {
              "branch": null,
              "revision": "3808ed0401379b6e9f4a053f03090ea9d658caa9",
              "version": "3.2.1"
            }
          },
          {
            "package": "Leaf",
            "repositoryURL": "https://github.com/vapor/leaf.git",
            "state": {
              "branch": null,
              "revision": "d35f54cbac723e673f9bd5078361eea74049c8d7",
              "version": "3.0.2"
            }
          },
          {
            "package": "MongoSwift",
            "repositoryURL": "https://github.com/mongodb/mongo-swift-driver.git",
            "state": {
              "branch": null,
              "revision": "dd26fc7e4dda121626c64e0205fba75bd435db23",
              "version": "0.1.3"
            }
          },
          {
            "package": "Multipart",
            "repositoryURL": "https://github.com/vapor/multipart.git",
            "state": {
              "branch": null,
              "revision": "f063180d0b84832accd33194e06ed3c41f8609ac",
              "version": "3.1.1"
            }
          },
          {
            "package": "Nimble",
            "repositoryURL": "https://github.com/Quick/Nimble.git",
            "state": {
              "branch": null,
              "revision": "6abeb3f5c03beba2b9e4dbe20886e773b5b629b6",
              "version": "8.0.4"
            }
          },
          {
            "package": "Routing",
            "repositoryURL": "https://github.com/vapor/routing.git",
            "state": {
              "branch": null,
              "revision": "d76f339c9716785e5079af9d7075d28ff7da3d92",
              "version": "3.1.0"
            }
          },
          {
            "package": "Service",
            "repositoryURL": "https://github.com/vapor/service.git",
            "state": {
              "branch": null,
              "revision": "fa5b5de62bd68bcde9a69933f31319e46c7275fb",
              "version": "1.0.2"
            }
          },
          {
            "package": "SQL",
            "repositoryURL": "https://github.com/vapor/sql.git",
            "state": {
              "branch": null,
              "revision": "50eaeb8f52a1ce63f1ff3880e1114dd8757a78a6",
              "version": "2.3.2"
            }
          },
          {
            "package": "SQLite",
            "repositoryURL": "https://github.com/vapor/sqlite.git",
            "state": {
              "branch": null,
              "revision": "314d9cd21165bcf14215e336a23ff8214f40e411",
              "version": "3.2.1"
            }
          },
          {
            "package": "bson",
            "repositoryURL": "https://github.com/mongodb/swift-bson",
            "state": {
              "branch": null,
              "revision": "40f770ed265bb9958edbcd0c809a3c2afe75a3ba",
              "version": "2.1.0"
            }
          },
          {
            "package": "mongoc",
            "repositoryURL": "https://github.com/mongodb/swift-mongoc",
            "state": {
              "branch": null,
              "revision": "e503b50210dae2cf0220474c2f12087830150e9f",
              "version": "2.0.0"
            }
          },
          {
            "package": "swift-nio",
            "repositoryURL": "https://github.com/apple/swift-nio.git",
            "state": {
              "branch": null,
              "revision": "ba7970fe396e8198b84c6c1b44b38a1d4e2eb6bd",
              "version": "1.14.1"
            }
          },
          {
            "package": "swift-nio-ssl",
            "repositoryURL": "https://github.com/apple/swift-nio-ssl.git",
            "state": {
              "branch": null,
              "revision": "0f3999f3e3c359cc74480c292644c3419e44a12f",
              "version": "1.4.0"
            }
          },
          {
            "package": "swift-nio-ssl-support",
            "repositoryURL": "https://github.com/apple/swift-nio-ssl-support.git",
            "state": {
              "branch": null,
              "revision": "c02eec4e0e6d351cd092938cf44195a8e669f555",
              "version": "1.0.0"
            }
          },
          {
            "package": "swift-nio-zlib-support",
            "repositoryURL": "https://github.com/apple/swift-nio-zlib-support.git",
            "state": {
              "branch": null,
              "revision": "37760e9a52030bb9011972c5213c3350fa9d41fd",
              "version": "1.0.0"
            }
          },
          {
            "package": "TemplateKit",
            "repositoryURL": "https://github.com/vapor/template-kit.git",
            "state": {
              "branch": null,
              "revision": "51405c83e95e8adb09565278a5e9b959c605e56c",
              "version": "1.4.0"
            }
          },
          {
            "package": "URLEncodedForm",
            "repositoryURL": "https://github.com/vapor/url-encoded-form.git",
            "state": {
              "branch": null,
              "revision": "82d8d63bdb76b6dd8febe916c639ab8608dbbaed",
              "version": "1.0.6"
            }
          },
          {
            "package": "Validation",
            "repositoryURL": "https://github.com/vapor/validation.git",
            "state": {
              "branch": null,
              "revision": "4de213cf319b694e4ce19e5339592601d4dd3ff6",
              "version": "2.1.1"
            }
          },
          {
            "package": "Vapor",
            "repositoryURL": "https://github.com/vapor/vapor.git",
            "state": {
              "branch": null,
              "revision": "92a58a9a84e4330500b99fe355a94d29f67abe58",
              "version": "3.3.1"
            }
          },
          {
            "package": "WebSocket",
            "repositoryURL": "https://github.com/vapor/websocket.git",
            "state": {
              "branch": null,
              "revision": "d85e5b6dce4d04065865f77385fc3324f98178f6",
              "version": "1.1.2"
            }
          }
        ]
      },
      "version": 1
    }
    

    What is the version(s) of mongod that you are running with the driver?

    db version v4.2.1
    git version: edf6d45851c0b9ee15548f0f847df141764a317e
    allocator: system
    modules: none
    build environment:
        distarch: x86_64
        target_arch: x86_64
    

    What is your server topology?

    How is your MongoDB deployment configured?

    Nothing special, just standard. Just a simple CRUD implementation with Vapor for an iOS App we use to get / update the data in our MongoDB ...
    

    How did you install libmongoc and libbson on your system

    Used Brew ...

    Version of libmongoc and libbson

    mongo-c-driver 1.15.1
    

    What is the problem?

    The implementation works, but sometimes ... after a few fetches from our iOS App, we get this warning (in the console):

    WARNING:       mongoc: Unknown rpc type: 0x00000000
    

    and the following error message in Xcode:

    NIO-ELT-#1 (5): signal SIGABRT
    

    Screenshot-2019-11-23-at-18-51-24

    Reproducing the bug

    1. Run Vapor app
    2. Load a few time from our iOS App ...
    3. And sometimes, after a while ..
    4. We get the warning
    opened by danieleftodi 10
  • bson_malloc memory leak

    bson_malloc memory leak

    Hi, there. I am experiencing massive memory leaks that seems to originate from bson_malloc. These calls are possibly originated by BSONDecoder. Running on macOS 10.14.4 / mongo driver 0.0.9 / mongo-c-driver 1.13.0

    Would be grateful if someone could help debugging the issue. Are you aware or have any suggestion on what could be the cause?

    Screenshot 2019-04-11 at 20 25 37

    opened by valeriomazzeo 10
  • [Question] Is there an equivalent of BsonIgnoreIfNullAttribute?

    [Question] Is there an equivalent of BsonIgnoreIfNullAttribute?

    I am having this very same problem: https://stackoverflow.com/questions/9917804/update-with-addtoset-not-updating-null-value-with-mongodb-c-sharp

    I wonder whether there's an equivalent of BsonIgnoreIfNullAttribute that can be used in the swift driver and if so, how to use it.

    https://api.mongodb.com/csharp/1.1/html/351f430e-5f7f-d97e-02e5-81b4f9c37d3f.htm

    opened by valeriomazzeo 9
Releases(v1.3.1)
  • v1.3.1(May 3, 2022)

    This release corrects a minor error that occurred during the 1.3.0 release process, where v1.3.0 was inadvertently tagged before the version string the driver reports in its handshake with the server was updated. As a result, "1.3.0-beta.1" would be incorrectly reported as the driver version in MongoDB server logs.

    There are no other changes from the 1.3.0 release.

    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(May 3, 2022)

    We are pleased to announce the GA of our 1.3.0 release, which contains no changes from our last pre-release, 1.3.0-beta.1.

    This release most notably adds the following features:

    Async/Await APIs

    This release adds a new async/await version of our entire API surface to allow you to start using the driver with Swift concurrency!

    For example, to create a collection and insert a document:

    let collection = try await db.createCollection("foo")
    try await collection.insertOne(["x": 1])
    

    We’ve also made MongoCursor and ChangeStream conform to AsyncSequence. This protocol provides a number of convenience methods for working with sequences, and enables you to consume their values via a for loop, for example:

    for try await doc in try await collection.find() {
        print(doc)
    }
    

    We’ve written a blog post that discusses this in more detail, and have also updated all of our documentation and our Vapor example project to use Swift concurrency to help you get started using these new APIs.

    These APIs are available for Swift 5.5.2+ developers on Linux and macOS 10.15+.

    Please feel free to file an issue if you run into any problems or have suggestions for improving the new APIs!

    New MongoConnectionString type

    This release also adds a new MongoConnectionString type modeling a MongoDB connection string, and moves the driver logic for parsing and validating a connection string, which was previously handled by the C driver, into the Swift layer.

    This type conforms to LosslessStringConvertible and so can be initialized via and converted to a String , and has mutable properties to allow setting/changing values. For example:

    var connStr = MongoConnectionString("mongodb://localhost:27017")
    connStr.readConcern = .local
    print(connStr) // prints "mongodb://localhost:27017/?readconcernlevel=local"
    

    You can now use this type to initialize a MongoClient:

    var connStr = MongoConnectionString("mongodb://localhost:27017")
    connStr.readConcern = .local
    let client = try MongoClient(connStr, using: yourEventLoopGroup)
    

    Included Tickets

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

    New Feature

    • [ SWIFT-1160 ] - Introduce new MongoConnectionString type
    • [ SWIFT-1161 ] - MongoConnectionString authentication options support
    • [ SWIFT-1162 ] - MongoConnectionString TLS options support
    • [ SWIFT-1163 ] - MongoConnectionString non-auth, non-TLS options support
    • [ SWIFT-1165 ] - Initialization of MongoClient via MongoConnectionString
    • [ SWIFT-1174 ] - MongoConnectionString Unix domain socket support
    • [ SWIFT-1384 ] - Support ‘let’ option for multiple CRUD commands
    • [ SWIFT-1389 ] - Implement MongoClient and ClientSession async/await APIs
    • [ SWIFT-1390 ] - Implement MongoDatabase async/await API methods
    • [ SWIFT-1391 ] - Implement MongoCollection async/await API methods
    • [ SWIFT-1392 ] - Make MongoCursor and ChangeStream conform to AsyncSequence
    • [ SWIFT-1405 ] - Implement description for MongoConnectionString
    • [ SWIFT-1407 ] - Support ipv4 address parsing in MongoConnectionString

    Improvement

    • [ SWIFT-1451 ] - Use -cross-module-optimization flag in Vapor example

    Task

    • [ SWIFT-1493 ] - Update vendored libmongoc to 1.21.0
    Source code(tar.gz)
    Source code(zip)
  • v1.3.0-beta.1(Mar 16, 2022)

    We are pleased to announce the first beta for our 1.3.0 driver release, which follows two previous alphas. We have recently gained the capability to test our new async APIs on macOS in CI (previously, we only could on Linux) and are moving toward a stable 1.3.0 GA release in the near future.

    Compared to the previous pre-release 1.3.0-alpha.2, this release contains a single bug fix, for SWIFT-1510.

    The bug was that, although we document that MongoCursor, ChangeStream and ClientSession will be automatically cleaned up upon deinit on any platform and Swift version where concurrency is available, this automatic cleanup would not actually occur on macOS < 12.

    Included Tickets

    • SWIFT-1510: Update #available statements for automatic cleanup logic in deinits to macOS 10.15+
    Source code(tar.gz)
    Source code(zip)
  • v1.3.0-alpha.2(Feb 24, 2022)

    We are pleased to announce the second alpha of our 1.3.0 release.

    The primary changes in this release from the previous alpha:

    • The minimum Swift version required to use the new async APIs has increased to Swift 5.5.2 from Swift 5.5.0, and the new async APIs are now available on macOS 10.15+, rather than macOS 12+. Thank you to @atultw for contributing these changes!
    • The driver’s vendors copy of libmongoc has been updated from version 1.19.2 to version 1.21.0. Please see the libmongoc release notes for details on the included changes.

    Contributors

    Thanks to everyone who contributed to this release!

    • @atultw
    • @isabelatkinson
    • @kmahar
    Source code(tar.gz)
    Source code(zip)
  • v1.3.0-alpha.1(Jan 28, 2022)

    We are pleased to announce the first alpha of our 1.3.0 release, containing the following new features:

    Async/Await APIs

    This release adds a new async/await version of our entire API surface to allow you to start using the driver with Swift concurrency!

    For example, to create a collection and insert a document:

    let collection = try await db.createCollection("foo")
    try await collection.insertOne(["x": 1])
    

    We’ve also made MongoCursor and ChangeStream conform to AsyncSequence. This protocol provides a number of convenience methods for working with sequences, and enables you to consume their values via a for loop, for example:

    for try await doc in try await collection.find() {
        print(doc)
    }
    

    We’ve written a blog post that discusses this in more detail, and have also updated all of our documentation and our Vapor example project to use Swift concurrency to help you get started using these new APIs.

    Currently, these APIs are available for Swift 5.5.0+ developers on Linux and macOS 12. For future alpha releases we are exploring making these APIs available on older macOS versions as well where concurrency has recently become available.

    Please feel free to file an issue if you run into any problems or have suggestions for improving the new APIs!

    New MongoConnectionString type

    This release also adds a new MongoConnectionString type modeling a MongoDB connection string, and moves the driver logic for parsing and validating a connection string, which was previously handled by the C driver, into the Swift layer.

    This type conforms to LosslessStringConvertible and so can be initialized via and converted to a String , and has mutable properties to allow setting/changing values. For example:

    var connStr = MongoConnectionString("mongodb://localhost:27017")
    connStr.readConcern = .local
    print(connStr) // prints "mongodb://localhost:27017/?readconcernlevel=local"
    

    You can now use this type to initialize a MongoClient:

    var connStr = MongoConnectionString("mongodb://localhost:27017")
    connStr.readConcern = .local
    let client = try MongoClient(connStr, using: yourEventLoopGroup)
    

    Included Tickets

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

    New Feature

    • [ SWIFT-1160 ] - Introduce new MongoConnectionString type
    • [ SWIFT-1161 ] - MongoConnectionString authentication options support
    • [ SWIFT-1162 ] - MongoConnectionString TLS options support
    • [ SWIFT-1163 ] - MongoConnectionString non-auth, non-TLS options support
    • [ SWIFT-1165 ] - Initialization of MongoClient via MongoConnectionString
    • [ SWIFT-1174 ] - MongoConnectionString Unix domain socket support
    • [ SWIFT-1384 ] - Support ‘let’ option for multiple CRUD commands
    • [ SWIFT-1389 ] - Implement MongoClient and ClientSession async/await APIs
    • [ SWIFT-1390 ] - Implement MongoDatabase async/await API methods
    • [ SWIFT-1391 ] - Implement MongoCollection async/await API methods
    • [ SWIFT-1392 ] - Make MongoCursor and ChangeStream conform to AsyncSequence
    • [ SWIFT-1405 ] - Implement description for MongoConnectionString
    • [ SWIFT-1407 ] - Support ipv4 address parsing in MongoConnectionString

    Improvement

    • [ SWIFT-1451 ] - Use -cross-module-optimization flag in Vapor example
    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Nov 9, 2021)

    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

    Bug

    • 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

    Improvement

    • 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

    Task

    • 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

    Contributors

    Thanks to everyone who contributed to this release!

    • @agolin95
    • @bynn
    • @isabelatkinson
    • @kmahar
    • @patrickfreed
    Source code(tar.gz)
    Source code(zip)
  • v1.2.0-beta.1(Sep 29, 2021)

    We are pleased to announce our first beta release for the upcoming 1.2.0 release of the Swift driver. We would love for you to try it out!

    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.

    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

    Bug

    • 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-904 - Add connectTimeoutMS option to MongoClientOptions
    • SWIFT-1157 - Implement ExpressibleByXLiteral for IndexHint
    • SWIFT-788 - Allow passing hint to findAndModify update and replace operations

    Improvement

    • SWIFT-910 - Lift restriction on authSource without credentials
    • SWIFT-1099 - Change estimatedDocumentCount() to use the $collStats Agg Stage Instead of Count Command
    • SWIFT-1100 - Implement change stream oplog parsing code for delta oplog entries
    • SWIFT-1107 - Mitigate pain of using field names with dots and dollars
    • SWIFT-1224 - Bump maxWireVersion for MongoDB 5.0
    • SWIFT-1307 - Expose serviceId in command monitoring events

    Task

    • SWIFT-1256 - Vendor libmongoc 1.19.0
    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(Jul 12, 2021)

    The MongoDB Swift driver team is pleased to announce our 1.1.1 release.

    This patch release is a recommended upgrade which updates the vendored MongoDB C driver code from version 1.17.4 to 1.17.7 and thus pulls in a number of bug fixes. You can find the details of the fixes included in the following C driver release notes: 1.17.7, 1.17.6, 1.17.5.

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Feb 19, 2021)

    The MongoDB Swift driver team is pleased to announce our 1.1.0 release.

    Highlights

    New BSON Library

    Last week, we released version 3.0.0 of SwiftBSON. This is a brand new, pure Swift BSON library. While the internals are all-new, the API is identical to the one that previously lived in the driver with a few additions as described in the release notes, and we've now switched the driver to depend on this library. For convenience, we re-export all symbols from SwiftBSON from MongoSwift and MongoSwiftSync, so you can continue to use BSON types as if they were defined directly in the driver with no breaking changes.

    Event Loop "Binding" for Core Async Driver Types

    Previously, there was no way to specify at the API level a particular EventLoop that a core driver type (client, database, or collection) should return EventLoopFutures on. We've now introduced a special EventLoopBoundClient type to support this for clients, and added support directly to MongoDatabase and MongoCollection for it as well. Please see our Multithreaded Usage Guide for more details.

    Aggregation Improvements

    We've added a new helper method to MongoDatabase via SWIFT-577 to support performing database-level aggregations.

    We've also added support via SWIFT-506 to both MongoDatabase.aggregate and MongoCollection.aggregate for specifying a Codable type that the returned MongoCursor should decode resulting documents into. Previously, these methods could only return MongoCursor<BSONDocument>s. For example:

    /// Collection type.
    struct Person: Codable {
        let _id: BSONObjectID
        let name: String
        let age: Int
        let favoriteColor: String
    }
    
    let coll = db.collection("people", withType: Person.self)
    try coll.insertMany([
        Person(_id: BSONObjectID(),  name: "Kaitlin", age: 26, favoriteColor: "blue")
        Person(_id: BSONObjectID(),  name: "Buffalo", age: 27, favoriteColor: "green")
    ]).wait()
    
    
    /// Transformed aggregation output type.
    struct PersonOutput: Codable {
        let name: String
        let age: Int
    }
    
    let resultsFuture = coll.aggregate([
        ["$project": ["age": 1, "name": 1, "_id": 0]] // only keep the age and name fields
    ], withOutputType: PersonOutput.self).flatMap { cursor in
        cursor.toArray()
    }
    
    // prints [PersonOutput(name: "Kaitlin", age: 26), PersonOutput(name: "Buffalo", age: 27)]
    print(try resultsFuture.wait())
    

    MongoClientOptions Improvements

    Previously, a number of driver options were only specifiable via connection string, and not supported via MongoClientOptions. We've now added support for specifying a number of options via the options struct as well, such as replicaSet and serverSelectionTimeoutMS.

    Included Tickets

    Bug

    • [SWIFT-957] - DecodingError when encountering dropDatabase event in change stream
    • [SWIFT-958] - Ensure nil is returned from cursor before returning LogicError
    • [SWIFT-969] - Manually clean up mongoc_uri_t when ConnectionString options validation fails
    • [SWIFT-974] - Cursor gets leaked in findOne after DecodingError
    • [SWIFT-1045] - MongoClient initializer performs blocking DNS lookup

    New Feature

    • [SWIFT-481] - Support index all paths
    • [SWIFT-828] - Hidden Indexes
    • [SWIFT-577] - Add database aggregation helper
    • [SWIFT-1028] - Create EventLoopBoundMongoClient type
    • [SWIFT-1029] - Implement EventLoop binding support for database and collection objects
    • [SWIFT-1030] - Implement EventLoop binding support for change streams and cursors
    • [SWIFT-1031] - Implement EventLoop binding support for sessions
    • [SWIFT-459] - Add a renameCollection helper
    • [SWIFT-519] - Support startAfter option for change streams
    • [SWIFT-506] - Allow users to specify the output type of an aggregation

    Task

    • [SWIFT-734] - Maintain multiple versions of the documentation
    • [SWIFT-791] - Support shorter SCRAM conversation
    • [SWIFT-854] - Organize API documentation in a more useful way
    • [SWIFT-936] - Update the driver to use the new BSON library
    • [SWIFT-1010] - Test against Swift 5.3 + Linux on Evergreen
    • [SWIFT-1034] - Update readme with how to sort all records after running collection.find()
    • [SWIFT-1092] - Vendor libmongoc 1.17.4
    • [SWIFT-763] - Deprecate geoHaystack and geoSearch

    Improvement

    • [SWIFT-805] - Make ExceededTimeLimit retryable writes error
    • [SWIFT-872] - Reduce default keepalive time to align with Azure defaults
    • [SWIFT-903] - Add compressors option to MongoClientOptions
    • [SWIFT-905] - Add heartbeatFrequencyMS option to MongoClientOptions
    • [SWIFT-906] - Add localThresholdMS option to MongoClientOptions
    • [SWIFT-907] - Add serverSelectionTimeoutMS option to MongoClientOptions
    • [SWIFT-909] - Add zLibCompressionLevel option to MongoClientOptions
    • [SWIFT-897] - Add appname option to MongoClientOptions
    • [SWIFT-898] - Add replicaSet option to MongoClientOptions
    • [SWIFT-901] - Add tlsInsecure option to MongoClientOptions
    • [SWIFT-912] - Error if minPoolSize option is provided in connection string
    • [SWIFT-929] - Validate options provided via MongoClientOptions
    • [SWIFT-1015] - Only create monitoring events if the user is actually subscribing to them
    • [SWIFT-1072] - Improve performance of insertion
    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(Jan 13, 2021)

    I'm pleased to announce our 1.0.2 release.

    This contains a fix (14afd20d3b2f75a373b990fa5ffcc5219ed2266e) for a memory leak on Linux: SWIFT-1051 / #571. Thank you to @NikolayJuly for bringing this to our attention.

    This leak was due to our usage of String.cString(using:), a Foundation method whose Linux implementation has apparently had a longstanding, known memory leak (see SR-4036, and the source code).

    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Aug 10, 2020)

    I'm pleased to announce our 1.0.1 release.

    This release contains a single bug fix for the issue raised in #387. Due to a bug in Xcode, cSettings defined in our Package.swift file were not being correctly applied to the driver when attempting to build it via Xcode's SwiftPM integration. We have now removed the need for the driver to use cSettings at all via #513. (See also: SWIFT-952) and the driver should build with Xcode + SwiftPM as expected.

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Jun 8, 2020)

    Today I'm very pleased to announce our 1.0 release.

    Our API is now stable, and from this point forward we'll follow semantic versioning.

    We'd like to thank the following people for helping us get to this release out:

    • @valeriomazzeo for raising #458, which led to the fix introduced in SWIFT-824 - as well as for opening various other issues over time!
    • @weissi and @lukasa for advice on fixing the issue encountered in SWIFT-779
    • The Swift Server Work Group for their thoughtful feedback and help moving through the SSWG pitch and proposal process (@tanner0101, @loganwright, @weissi, @tomerd)
    • Numerous others who have contributed code, feedback, and bug reports to the driver over the last 2 years!

    This release was preceded by 2 release candidates (rc0, rc1); if you are upgrading from an earlier version of the driver, please see their respective release notes for details on what has changed since v0.3.0.

    Below are some changes of note we've made, as well as a list of all tickets we've closed since 1.0.0-rc1.

    Notable Changes

    macOS Version Support

    The minimum macOS version the driver now supports is 10.14.

    Errors

    To improve the discoverability of driver error types, their definitions have now all been nested in an enumeration MongoError. The old protocol MongoError has been renamed MongoErrorProtocol. Additionally, a separate namespace and set of errors have been introduced for use within the BSON library. Please see our error handling guide for more details.

    BSON API

    We've made some naming changes to the BSON library to prevent collisions with other libraries as well as to provide more consistency within the library as a whole. Please see the migration guide section of our BSON guide for details on upgrading from 1.0.0-rc1's API.

    Renamed Types

    In addition to prefixing some types in the BSON library, we've also made the following renames in the driver:

    • ClientOptions is now MongoClientOptions
    • DatabaseOptions is now MongoDatabaseOptions
    • CollectionOptions is now MongoCollectionOptions
    • Hint is now IndexHint
    • Address is now ServerAddress
    • CursorType is now MongoCursorType
    • The enum case WriteConcern.W.tag is now WriteConcern.W.custom

    Initial Replica Set Discovery Behavior

    The driver's behavior around initial discovery of replica set members has changed as of SWIFT-742.

    Consider the following scenario: you have a three-node replica set with hosts running at localhost:27017, localhost:27018, and localhost:27019. Previously, given a connection string containing a single one of those hosts (e.g. mongodb://localhost:27017) the driver would make a direct connection to that host only, and would not attempt to discover or monitor other members of the replica set.

    The driver's default behavior is now to automatically attempt discovery of the entire replica set when given a single host.

    If you need to establish a direction connection, you can use the new connection string option directConnection=true, or set MongoClientOptions.directConnection to true. Omitting the option is equivalent to setting it to false.

    More Complex Vapor Example Application

    We've added a new Vapor example, demonstrating how to use the driver within the context of a CRUD application. If you have any suggestions for improvement or other example code you'd like to see added, please let us know!

    Included Tickets

    Bug

    • [SWIFT-779] - Investigate issue with 5.2 release mode C interop
    • [SWIFT-824] - Use stack allocated bson_ts for all reply documents
    • [SWIFT-761] - Fix thread sanitizer warnings

    Task

    • [SWIFT-826] - Make Date(msSinceEpoch:) internal
    • [SWIFT-850] - Rename Id -> ID
    • [SWIFT-851] - Namespace all error types within an enum
    • [SWIFT-855] - Drop support for macOS versions < 10.14
    • [SWIFT-870] - Add default value for BSON.objectID case
    • [SWIFT-878] - Define BSON specific error types

    Improvement

    • [SWIFT-742] - Unify behavior around configuration for replica set discovery
    • [SWIFT-204] - Suppress "ns not found" errors in MongoCollection.drop()
    • [SWIFT-769] - localizedDescription of errors should contain error message
    • [SWIFT-815] - More convenient API for ReadConcern/WriteConcern creation
    • [SWIFT-822] - Add prefixes to public type names where needed
    • [SWIFT-827] - Rewrite enums with .other case as structs
    • [SWIFT-835] - Standardize on conversion method names
    • [SWIFT-863] - Rename WriteConcern.W tag case to custom
    • [SWIFT-882] - Rewrite extJSON properties as functions
    • [SWIFT-640] - Add authentication options to MongoClientOptions
    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(May 12, 2020)

    We are pleased to announce our 0.3.0 release.

    This release is identical to the 0.2.0 release except for a single ticket, SWIFT-823, which drops support for Swift 5.0 and updates the way we link to system installations of the MongoDB C driver to be compatible with Swift 5.2.

    This release is intended to provide an upgrade path to our 1.0 release for users, allowing you to first upgrade to Swift 5.2 and then to separately upgrade to a newer driver version. At this time we do not plan on tagging further 0.3.x releases. For new users, we strongly suggest pinning to the latest 1.0 release candidate:

    .package(url: "https://github.com/mongodb/mongo-swift-driver", .exact("1.0.0-rc1"))
    
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-rc1(May 5, 2020)

    We are pleased to announce the second release candidate for our 1.0.0 release.

    Please note that this release drops support for Swift 5.0. The driver officially supports Swift 5.1 and 5.2 on macOS, Ubuntu 16.04, and Ubuntu 18.04.

    A full list of included tickets is available below, but here are some highlights:

    New Feature: Transactions Support

    The driver now provides an API for transactions! Note that MongoDB supports transactions in replica sets as of v4.0, and in sharded clusters as of v4.2.

    Please see the Transactions Guide in our documentation for details and examples.

    Work on the convenient API for transactions (i.e. a withTransaction helper that includes helpful logic to automatically retry transactions on certain errors) is currently in progress.

    Notable API Changes

    • MongoClient.shutdown() and MongoClient.syncShutdown() have been renamed MongoClient.close() and MongoClient.syncClose(), respectively, for consistency with other MongoDB drivers. (SWIFT-749)
    • ReadPreference is now a struct rather than a class. It no longer has any public initializers, but is instead initializable via static properties and methods available on the type. This makes usages more succinct, particularly in the context of e.g. an options struct where the compiler can infer the type. (SWIFT-738) Example:
      let rp = ReadPreference(.primary) // old
      let rp = ReadPreference.primary // new
      
      let rp = try ReadPreference(.secondary, maxStalenessSeconds: 100) // old
      let rp = try ReadPreference.secondary(maxStalenessSeconds: 100) // new
      
      let options = FindOptions(readPreference: ReadPreference(.primary)) // old
      let options = FindOptions(readPreference: .primary) // new
      
    • All of the TLS options previously specifiable via the TLSOptions struct have been moved directly into ClientOptions, and have been renamed for consistency with the names used when they are specified via a MongoDB connection string. (SWIFT-753)
    • The maxScan option which has been deprecated since MongoDB v4.0 has been removed from FindOptions and FindOneOptions. (SWIFT-439)
    • Several previous usages of other integer types in the API have been updated to use Int instead (SWIFT-754). Please see 940d90d9e8879fd09a8cb5f7a17aa4ca29bb6617 for a complete list.

    Included Tickets

    Bug

    • [SWIFT-750] - fix potential for deadlock when all connections are in use

    New Feature

    • [SWIFT-746] - Implement startTransaction, commitTransaction, and abortTransaction in the asynchronous API
    • [SWIFT-747] - Implement startTransaction, commitTransaction, and abortTransaction in the synchronous API

    Task

    • [SWIFT-434] - Add a TLS guide
    • [SWIFT-743] - Implement TransactionOptions struct
    • [SWIFT-752] - Implement Transactions Spec Test Runner
    • [SWIFT-347] - Update error handling guide to include errorLabels information
    • [SWIFT-439] - Remove maxScan query option
    • [SWIFT-499] - Update benchmark suite to include multithreaded scenarios
    • [SWIFT-595] - Bump libmongoc version to 1.16
    • [SWIFT-618] - Bump minimum Swift version to 5.1, and start testing against Swift 5.2
    • [SWIFT-636] - Stop filtering out SERVICE_NAME = mongodb from mechanism properties in GSSAPI auth tests ( [SWIFT-705] - Tune default NIOThreadPool size
    • [SWIFT-731] - Update guides to focus on async API
    • [SWIFT-735] - Make ObjectId work with JSONEncoder/JSONDecoder
    • [SWIFT-744] - Update ClientSessionOptions to support transactions
    • [SWIFT-745] - Implement StartTransactionOperation, CommitTransactionOperation, and AbortTransactionOperation
    • [SWIFT-784] - Disable BSON_EXTRA_ALIGN in vendored libbson
    • [SWIFT-423] - Provide Transactions example for Docs

    Improvement

    • [SWIFT-224] - Avoid roundtripping values through Swift when copying values from one document to another
    • [SWIFT-621] - Provide default values for enum associated values where appropriate
    • [SWIFT-623] - Use Self rather than type(of: self)
    • [SWIFT-677] - listIndexNames should extract names from Documents rather than decoding entire IndexModels
    • [SWIFT-753] - Condense TLSOptions into ClientOptions struct, and make property names consistent with URI options spec
    • [SWIFT-754] - Use Int in public API as much as possible
    • [SWIFT-757] - Add RetryableWriteError error labels to retryable transaction tests
    • [SWIFT-772] - Add allowDiskUse option to find command
    • [SWIFT-751] - Add maxPoolSize option for connection pool
    • [SWIFT-773] - Support for authorizedDatabases option
    • [SWIFT-749] - Improve MongoClient shutdown logic
    • [SWIFT-738] - Make ReadPreference a struct
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-rc0(Feb 27, 2020)

    MongoSwift 1.0.0-rc0

    We are very excited to announce the first release candidate for our upcoming 1.0.0 release.

    This release contains a number of major changes to the driver, as detailed in the following sections.

    Asynchronous, SwiftNIO-based API

    The driver now contains both asynchronous and synchronous APIs for working with MongoDB from Swift. These APIs are contained in two modules, named MongoSwift (async) and MongoSwiftSync (sync). Depending on which API you would like to use, you can depend on either one of those modules.

    The asynchronous API is implemented by running all blocking code off the calling thread in a SwiftNIO NIOThreadPool. The size of this thread pool is configurable via the threadPoolSize property on ClientOptions.

    Vapor developers: please note that since we depend on SwiftNIO 2, as of this reelase the driver will not be compatible with Vapor versions < 4, as Vapor 3 depends on SwiftNIO 1.0.

    All of the web framework examples in the Examples/ directory of this repository have now been updated to use the asynchronous API.

    The synchronous API has been reimplemented as a wrapper of the asynchronous API. You may also configure the size of the thread pool when constructing a synchronous MongoClient as well.

    If you are upgrading from a previous version of the driver and would like to continue using the synchronous API, you should update your Package.swift to make your target depend on MongoSwiftSync, and replace every occurrence of import MongoSwift with import MongoSwiftSync.

    The MongoDB C driver is now vendored and built via SwiftPM

    Previously, the driver would link to a system installation of the MongoDB C driver, libmongoc. We have now vendored the source of libmongoc into the driver, and it is built using SwiftPM.

    libmongoc does link to some system libraries itself for e.g. SSL support, so depending on your operating system and system configuration you may still need to install some libraries. Please see the updated installation instructions for more details.

    Note: Unfortunately, due to an issue with the Xcode SwiftPM integration where Xcode ignores cSettings (necessary for building libmongoc), as of Xcode 11.3 the driver currently cannot be added to your project as a dependency in that matter. Please see #387 and SR-12009 for more information. In the meantime, you can work around this by:

    1. Add the driver to your Package.swift file
    2. Run swift package generate-xcodeproj from the command line
    3. Open the resulting .xcodeproj in Xcode

    Alternatively, as described in #387 you can clone the driver, run make project from its root directory to generate a corresponding .xcodeproj, and add that to an Xcode workspace.

    Driver Error Types are now structs

    Like many Swift libraries, the driver previously used enums to represent a number of different error types. However, over time we realized that enums were a poor fit for modeling MongoDB errors. Anytime we wished to add an additional associated value to one of the error cases in an enum, or to add a new case to one of the enums, it would be a breaking change. Over time the MongoDB server has added more and more information to the errors it returns, and has added various new categories of errors. Enums made it difficult for our errors to evolve gracefully along with the server.

    Now, each type of error that was previously an enum case is represented as a struct, and similar errors are grouped together by protocols rather than by being cases in the same enum.

    Please see the updated error handling guide for more information on the types of errors and best practices for working with them.

    Synchronous Cursor and Change Stream API Updates

    Use of Result

    The synchronous variants of MongoCursor and ChangeStream (defined in MongoSwiftSync) now return a Result<T>? from their next() methods rather than a T?. You can read more about the Swift Standard Library's Result type here. This change enables to propagate errors encountered while iterating, for example a network error, via a failed Result. Previously, users had to inspect the error property of a cursor/change stream, which was unintuitive and easy to forget.

    Iterating over a cursor would now look like this:

    for result in cursor {
        switch result {
        case let .success(doc):
            // do something with doc
        case let .failure(error):
            // handle error    
        }
    }
    

    Alternatively, you may use the get method on Result:

    for result in cursor {
        let doc = try result.get()
        // do something with doc
    }
    

    Since errors are now propagated in this way, the error property has been removed from both types and inspecting it is no longer necessary.

    next() now blocks while waiting for more results

    This change only affects ChangeStreams and tailable MongoCursors. (See: change streams, tailable cursors.) (By default, cursors are not tailable.) These types will stay alive even after their initial results have been exhausted, and will continue to receive new matching documents (or events in the case of change streams) if and when they become available.

    In the past, next() would simply return nil immediately if a next result was not available. This would require a user who wants to wait for the next result to continuously loop and check for a non-nil result. Now, next() will internally poll until a new result is obtained or the cursor is killed (you can trigger this yourself by calling kill).

    If you wish to use the old behavior where the method would not continuously poll and look for more results, you can use the newly introduced tryNext() which preserves that behavior.

    For non-tailable MongoCursors, the cursor is automatically killed as soon as all currently available results are retrieved, so next() will behave exactly the same as tryNext().

    Note that a consequence of this change is that working with a tailable MongoCursor or a ChangeStream via Sequence methods or a for loop can block while waiting for new results, since many Sequence methods are implemented via next().

    Conformance to LazySequenceProtocol

    MongoCursor and ChangeStream now conform to LazySequenceProtocol, which inherits from Sequence (which these types conformed to previously).

    This allows the standard library to defer applying operations such as map and filter until the elements of the resulting Sequence are actually accessed. This is beneficial for cursors and change streams as you can transform their elements without having to load the entire result set into memory at once. For example, consider the following snippet. The map call will be lazily applied as each element is read from the cursor in step 3:

    // 1. Create a cursor
    let cursor = try myCollection.find()
    
    // 2. Add a call to `map` that transforms each result in the cursor by adding a new key
    let transformed = cursor.map { result in
        // try to get the result, and if we succeed add a key "a" to it. if we fail, return
        // a failed result containing the error
        Result { () throws -> Document  in
            var doc = try result.get()
            doc["a"] = 1
            return doc
        }
    }
    
    // 3. Iterate the transformed cursor
    for result in transformed {
        // ...
    }
    

    Note: If you wish to take advantage of LazySequenceProtocol, you cannot throw from the closure passed to map / filter / etc. Those variants only exist on Sequence, and calling them will result in the sequence being eagerly loaded into memory before the closure is applied.

    Improved Monitoring API

    More Flexible Event Handling

    Prior to this release, MongoClient posted all monitoring events to a NotificationCenter, either one provided to it via ClientOptions or the application's default center. This was overly restrictive, as it required you to interface with NotificationCenter in order to receive monitoring events, even if NotificationCenter wasn't used anywhere else in your application.

    Starting in this release, you can attach your own handler types that conform to the new CommandEventHandler and SDAMEventHandler protocols to via MongoClient.addCommandEventHandler and MongoClient.addSDAMEventHandler respectively. The appropriate monitoring events will then be passed to them directly via the protocol requirement methods. From there, you can do whatever processing of the events you want, including, but not limited to, posting to a NotificationCenter.

    Also, there are ergonomic overloads for both of the handler adding methods that take in callbacks if you don't want to define your own handler type:

    client.addCommandEventHandler { event in
        print(event)
        // be sure not to strongly capture client in here!
    }
    

    Restructured Event Types

    Prior to this release, all monitoring events were defined as their own structs, and extracting the right event type required lots of downcasting. Starting in this release, common event types are grouped into enums, namely into the SDAMEvent and CommandEvent enums, whose cases' associated values are the existing event structs. This models events in a way that makes better use of the Swift type system by removing the need for downcasting, allowing like events to be grouped together, and enabling relevant event types to be switched over exhaustively.

    Included Tickets

    Bug

    • [SWIFT-663] - Stop parsing write concern errors when extracting bulk write errors

    New Features

    • [SWIFT-410] - Async API
    • [SWIFT-643] - Add a findOne method
    • [SWIFT-718] - Implement toArray method for async cursors and change streams
    • [SWIFT-719] - Implement forEach method for async cursors and change streams
    • [SWIFT-360] - More flexible monitoring API

    Improvement

    • [SWIFT-500] - Vendor libmongoc and build it with SwiftPM
    • [SWIFT-675] - Iterate over Result<T> in MongoCursor
    • [SWIFT-688] - Iterate over Result<T> in ChangeStream
    • [SWIFT-661] - Make find and aggregate do immediate I/O
    • [SWIFT-314] - Gracefully handle errors parsing isMaster responses for SDAM monitoring
    • [SWIFT-502] - Reimplement errors as structs
    • [SWIFT-601] - Introduce protocol(s) for SDAM monitoring events

    Task

    • [SWIFT-288] - Make use of new libmongoc function for getting a server's lastUpdateTime
    • [SWIFT-427] - Remove autoIndexId option for collection creation
    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Dec 18, 2019)

    We are pleased to announce the 0.2.0 release of the MongoDB Swift driver.

    This release includes a number of major improvements, detailed in the following sections.

    Please note that as of this release we now require using Swift version 5.0 or greater, and version 1.15.3 or greater of the MongoDB C driver.

    Thank you to everyone who contributed to this release!

    Improvements for use in multithreaded applications

    MongoClients now automatically pool connections to the server. We recommend sharing clients across threads in your application when possible in order to decrease the total number of connections to the server your application has open at a time.

    MongoClient, MongoDatabase, and MongoCollection are now all safe to share across threads.

    Please see our new multithreading guide for more information.

    New BSON API

    We've significantly changed the API for the driver's BSON library to make using BSON types and constructing Documents much easier.

    Please see our guide describing how to use the BSON library, including a migration guide for updating from the old API.

    Other new features of note

    A number of other new features have been added since our last release, including:

    • Change streams support (please see our guide on using change streams here)
    • API for specifying TLS options for use with a MongoClient

    Included tickets

    Bug

    • [SWIFT-395] - wtimeoutMS is truncated if set to a value > Int32.max

    New Feature

    • [SWIFT-133] - Implement new count API
    • [SWIFT-173] - Implement Initial DNS Seedlist discovery spec
    • [SWIFT-174] - Implement Database Enumeration spec
    • [SWIFT-176] - Implement change streams API and basic tests
    • [SWIFT-178] - All writes retryable support
    • [SWIFT-374] - Integrate libmongoc client pool into operation execution
    • [SWIFT-471] - Allow user-specified SSL options at the client level
    • [SWIFT-489] - Errors raised by drivers should include codeName string from server response
    • [SWIFT-561] - Document connection string and URI option precedence rules
    • [SWIFT-587] - Retryable Reads
    • [SWIFT-629] - Introduce the BSON enum
    • [SWIFT-630] - Integrate BSON enum into the existing API and update tests

    Task

    • [SWIFT-364] - Update minimum required version to libmongoc 1.15.3
    • [SWIFT-389] - Remove deprecated bsonEquals functions
    • [SWIFT-632] - Drop Swift 4.2 support
    • [SWIFT-645] - Remove ReadConcern(_ doc: Document) initializer
    • [SWIFT-656] - Remove embedded driver
    • [SWIFT-659] - Document should not conform to ExpressibleByArrayLiteral

    Improvement

    • [SWIFT-185] - Support maxTimeMS for createIndexes and dropIndexes command
    • [SWIFT-215] - Array should conditionally conform to BSONValue
    • [SWIFT-320] - All BSONValue types should be Hashable using 4.2+ Hashable API
    • [SWIFT-375] - Ensure MongoClient, MongoCollection and MongoDatabase are thread safe
    • [SWIFT-412] - MongoDatabase.drop and MongoCollection.drop should allow specifying a WriteConcern
    • [SWIFT-501] - Rationalize how we handle client options provided in URI vs. options struct
    • [SWIFT-503] - Validate that w and wtimeoutMS are non-negative in WriteConcern initializer
    • [SWIFT-504] - ReadConcern and WriteConcern should no longer wrap mongoc types
    • [SWIFT-513] - Standardize on parameter ordering for options initializers
    • [SWIFT-514] - Make MongoDatabase and MongoCollection structs
    • [SWIFT-515] - Rationalize handling of server default vs. not-provided read concern, write concern
    • [SWIFT-517] - Return Connection to pool as soon as MongoCursor is exhausted
    • [SWIFT-522] - Move listCollections filter to top level
    • [SWIFT-526] - Standardize index command options
    • [SWIFT-600] - Decimal128.writeToCurrentPosition should pass a non-mutable pointer to bson_iter_overwrite_decimal128
    • [SWIFT-607] - Implement collection enumeration spec
    • [SWIFT-608] - Implement index enumeration spec
    Source code(tar.gz)
    Source code(zip)
  • v0.1.3(Jun 4, 2019)

  • v0.1.1(Jun 4, 2019)

    We are pleased to announce the 0.1.1 release of the MongoDB Swift driver.

    Release Highlights

    Sessions support

    This release adds support for MongoDB client sessions. This allows the driver to make certain causal consistency guarantees for operations that are executed using the same session, depending on the write/read concern configuration. See the official MongoDB documentation for more information on these guarantees, and the documentation on ClientSession for example usage.

    Simpler Initialization and Cleanup

    Previously, we required that users call MongoSwift.initialize() before using the driver to set up some global state and resources. We've now deprecated this method, and made it so that initialization happens automatically the first time you create a MongoClient.

    Additionally, note that MongoSwift.cleanup() (which should be called exactly once when your application is done using the driver) has been deprecated and renamed cleanupMongoSwift(). Please see SWIFT-402 for context on the name change.

    Mutable options structs

    All of the properties stored in options structs are now vars, allowing you to do things like:

    var options = FindOptions()
    options.batchSize =  10
    options.skip = 5
    

    Included tickets

    Bug

    • [SWIFT-404] - expireAfter index option is not correctly encoded
    • [SWIFT-405] - Document.count should not be publicly settable

    New Feature

    Improvement

    • [SWIFT-311] - MongoClient/MongoDatabase/MongoCollection ReadPreference getters should not return Optionals
    • [SWIFT-355] - Make options properties mutable to allow changing them after creation
    • [SWIFT-402] - Handle MongoSwift name conflicts
    • [SWIFT-413] - Make properties of WriteModel implementations public
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Apr 18, 2019)

    We are pleased to announce the 0.1.0 release of the MongoDB Swift driver.

    Release Highlights

    Swift 5 Support

    This release adds support for using the driver in Swift 5.0. It also drops support for Swift versions < 4.2.

    Improved Error Reporting

    This release re-organizes the errors thrown by the driver to more accurately represent their sources. In particular, we now throw four classes of errors: ServerError, UserError, RuntimeError, and EncodingError/DecodingError. Each type is described in detail in the error handling guide.

    BSON Improvements

    This release includes a number of improvements to the BSON library. In particular:

    Improved Int Handling consistency in Document

    We've improved the consistency of how Ints are read from and written to Documents. Previously, Int was encoded to BSON as an int32 if it could fit, or an int64 otherwise. This could lead to situations where Ints were not round tripped properly through Documents. Now, Int behaves as the type of integer it represents on a given architecture, which means it is always round-tripped correctly. (See here for details on Swift Int's variable bitwidth.)

    On 64-bit systems:

    • Int is encoded as a BSON int64
    • BSON int32s are read out of documents as Int32s
    • BSON int64s are read out of documents as Ints
    • e.g. doc["a"] = 5 sets the "a" key of a document to the BSON int64 5, and doc["a"] returns Int(5)

    On 32-bit systems:

    • Int is encoded as a BSON int32
    • BSON int32s are read out of documents as Ints
    • BSON int64s are read out of documents as Int64s

    On both systems, Int32 and Int64 are encoded to BSON int32 and BSON int64, respectively.

    BSONNumber

    To facilitate writing architecture-independent code (which is rare, since Swift support for 32-bit is extremely limited), we introduced the BSONNumber protocol, which all the numeric BSONValue types (Int32, Int64, Int, Double, and Decimal128) conform to. Conformance to this protocol allows conversion to any of the number types that BSON natively supports. However, the conversions will only return a value if the conversion is exact, and will return nil otherwise.

    let a: BSONNumber = 5.2
    a.int32Value // nil
    a.doubleValue // Double(5.2)
           
    let b: BSONNumber = 5.0
    b.int32Value // int32(5)
    b.doubleValue // Double(5.0)
       
    let c: BSONNumber = Int32.max + 1
    c.int32Value // nil
    c.int64Value // Int64(2147483648)
    
    // Example usage for when you know it's a number, but not what type of number it is and/or you don't care
    let doc: Document = ["a": 5.0]
    (doc["a"] as! BSONNumber).intValue // 5
    

    New Types for Deprecated BSON Types

    We've added new types for deprecated BSON types: Undefined, DBPointer, and Symbol. Previously, when extracted from a Document, values encoded as those types would be automatically converted to similar non-deprecated ones. Their types are now preserved.

    bsonEquals added to BSONValue protocol

    bsonEquals is now part of the BSONValue protocol. Statements that were previously written as bsonEquals(a, b) can now be written as a.bsonEquals(b). The old syntax is deprecated and will be removed in a future release.

    Coding Strategies Introduced

    We've introduced the concept of a Coding Strategy in this release, which allows the user to specify how certain values get encoded to and decoded from BSON using BSONEncoder / BSONDecoder. The provided strategies are heavily based on the encoding and decoding strategies used in Foundation's JSONEncoder/JSONDecoder, and are implemented to behave similarly. See the driver documentation (and Foundations docs) for information on how they can be used. An in-depth guide is forthcoming for usage in the driver.

    let date = Date(timeIntervalSince1970: 1.5)
    let codingOptions = BSONCoderOptions(dateCodingStrategy: .millisecondsSince1970)
    let doc = try BSONEncoder(options: codingOptions).encode(["a": date]) // ["a": Int64(1500)]
    try BSONDecoder(options: codingOptions).decode(DateWrapperA.self, from: doc).a.timeIntervalSince1970 // 1.5
    

    Release Notes

    Bug

    • [SWIFT-294] - TopologyDescription initializer doesn't clean up server descriptions array
    • [SWIFT-351] - Correctly encode strings with multi-byte UTF8 characters
    • [SWIFT-394] - Ensure all bson_ts are correctly cleaned up

    New Feature

    • [SWIFT-276] - Implement workaround for Swift 5.0 byte alignment cap to enable Swift 5 support
    • [SWIFT-337] - Support setting of encoding/decoding strategies on client, database, and collection levels

    Improvement

    • [SWIFT-144] - Update CRUD API errors to match the new hierarchy
    • [SWIFT-221] - Provide better consistency around Int usage with Documents
    • [SWIFT-268] - Store bson_oid_t in ObjectId rather than creating one each time we need it
    • [SWIFT-299] - Introduce new errors and error types
    • [SWIFT-300] - Convert InsertManyResult to BulkWriteResult when insertMany throws BulkWriteError
    • [SWIFT-301] - Convert invalidCollection, invalidClient, invalidUri, and invalidResponse errors to internalError or fatalError
    • [SWIFT-302] - Convert invalidCursor errors to commandErrors, logicErrors and invalidArgument errors
    • [SWIFT-303] - Convert bsonParseError to internalError
    • [SWIFT-304] - Convert bsonEncodeError, bsonDecodeError, typeError to new error types
    • [SWIFT-305] - Convert readPreferenceError to invalid argument or logic errors
    • [SWIFT-310] - Remove old errors
    • [SWIFT-313] - Move RegularExpression.nsRegularExpression logic into a new NSRegularExpression initializer
    • [SWIFT-331] - Throw an error when a non-BSONEncoder is used in encode(to:) for all BSONValue types that we own
    • [SWIFT-332] - Throw an error when non-BSONDecoder is used in init(from: decoder) for BSONValue types
    • [SWIFT-352] - Test round-tripping of BSON types with native representations using the BSON corpus data
    • [SWIFT-356] - Round trip Symbols, DBPointers, and Undefineds correctly
    • [SWIFT-358] - Don't require connectionString label in MongoClient initializer
    • [SWIFT-372] - Include bsonEquals as part of BSONValue protocol
    • [SWIFT-379] - Improve error message for type mismatches when decoding driver introduced BSON types
    • [SWIFT-384] - Provide an internal accessor for `bson_t`s length
    • [SWIFT-390] - Make bson pointer access explicit
    Source code(tar.gz)
    Source code(zip)
MySQL driver for Swift 3 (macOS and Linux)

MySQL MySQL Usage // do your magic Installation import PackageDescription let package = Package( dependencies: [ .Package(url: "https://g

Zewo Graveyard 29 Jan 29, 2022
Commmunity-supported Swift Driver for FaunaDB

Commmunity-supported Swift Driver for FaunaDB FaunaDB's Swift driver is now "community-supported". New features won't be exposed in the driver unless

Fauna, Inc. 22 May 30, 2022
A stand-alone Swift wrapper around the mongo-c client library, enabling access to MongoDB servers.

This package is deprecated in favour of the official Mongo Swift Driver. We advise users to switch to that pack

PerfectlySoft Inc. 54 Jul 9, 2022
A MongoDB interface for Swift [Not under active development]

MongoDB #This library is no longer under active development. I highly recommend using the robust, pure-swift alternative MongoKitten. A Swift MongoDB

Dan Appel 266 Jan 29, 2022
This Project domonstrate the latest Swift on Server to create RESTFul API's connected via Database: MongoDB NoSql

Swift is a general-purpose programming language built using a modern approach to safety & performance that make it specifically suitable for Server applications. Vapor is a web framework for Swift, allowing you to write backends, web apps APIs and HTTP servers in Swift

Furqan 3 Aug 23, 2022
SQLite.swift - A type-safe, Swift-language layer over SQLite3.

SQLite.swift provides compile-time confidence in SQL statement syntax and intent.

Stephen Celis 8.7k Jan 3, 2023
🧡 SQLiteOrm-Swift is an ORM library for SQLite3 built with Swift 5

?? Easy to use SQLite ORM library written with Swift

Yevgeniy Zakharov 25 Oct 6, 2022
ObjectBox Swift - persisting your Swift objects superfast and simple

ObjectBox Swift ObjectBox is a superfast, light-weight object persistence framework. This Swift API seamlessly persists objects on-device for iOS and

ObjectBox 380 Dec 19, 2022
Shows the issue with swift using an ObjC class which has a property from a swift package.

SwiftObjCSwiftTest Shows the issue with swift using an ObjC class which has a property from a swift package. The Swift class (created as @objc derived

Scott Little 0 Nov 8, 2021
Ios-App-ication-Swift - A simple iOS application made in Xcode using Swift

?? iPhone Calculator A simple iOS application made in Xcode using Swift. This ap

Kushal Shingote 1 Feb 2, 2022
Save-the-dot-project-swift - Save the dot project with swift

Save the Dot Apple introduced UIViewPropertyAnimator for iOS 10. We can use this

Kushal Shingote 2 Feb 8, 2022
The Swift Package Index is the place to find Swift packages!

The Swift Package Index helps you make better decisions about the dependencies you use in your apps. The Swift Package Index is a search engine for pa

Swift Package Index 389 Dec 22, 2022
Elegant library to manage the interactions between view and model in Swift

An assistant to manage the interactions between view and model ModelAssistant is a mediator between the view and model. This framework is tailored to

Seyed Samad Gholamzadeh 28 Jan 29, 2022
CRUD is an object-relational mapping (ORM) system for Swift 4+.

CRUD is an object-relational mapping (ORM) system for Swift 4+. CRUD takes Swift 4 Codable types and maps them to SQL database tables. CRUD can create tables based on Codable types and perform inserts and updates of objects in those tables. CRUD can also perform selects and joins of tables, all in a type-safe manner.

PerfectlySoft Inc. 61 Nov 18, 2022
CoreXLSX is a Excel spreadsheet (XLSX) format parser written in pure Swift

CoreXLSX Excel spreadsheet (XLSX) format parser written in pure Swift CoreXLSX is a library focused on representing the low-level structure of the XML

null 684 Dec 21, 2022
Solutions to LeetCode by Swift

LeetCode by Swift LeetCode Online Judge is a website containing many algorithm questions. Most of them are real interview questions of Google, Faceboo

Soap 4.5k Jan 5, 2023
Super lightweight DB written in Swift.

Use of value types is recommended and we define standard values, simple structured data, application state and etc. as struct or enum. Pencil makes us store these values more easily.

Naruki Chigira 88 Oct 22, 2022
YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.

YapDatabase is a collection/key/value store and so much more. It's built atop sqlite, for Swift & Objective-C developers, targeting macOS, iOS, tvOS &

Yap Studios 3.3k Dec 29, 2022
CoreData/Realm sweet wrapper written in Swift

What is SugarRecord? SugarRecord is a persistence wrapper designed to make working with persistence solutions like CoreData in a much easier way. Than

Modo 2.1k Dec 9, 2022