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

Build Status Code Coverage

MongoSwift

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

Index

Documentation

The latest documentation 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.

Installation

MongoSwift works with Swift 5.0+ on MacOS and Linux.

Installation is supported via Swift Package Manager.

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 MongoSwift

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 BSON implementation and a number of core types such as options structs.

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

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "MyPackage",
    dependencies: [
        .package(url: "https://github.com/mongodb/mongo-swift-driver.git", from: "VERSION.STRING.HERE"),
    ],
    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:

import MongoSwift
import NIO

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

defer {
    // clean up driver resources
    client.syncShutdown()
    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:

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

Sync:

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

Find Documents

Async:

let query: Document = ["a": 1]
let result = collection.find(query).flatMap { cursor in
    cursor.forEach { doc in
        print(doc)
    }
}

Sync:

let query: Document = ["a": 1]
let documents = try collection.find(query)
for d in documents {
    print(try d.get())
}

Work With and Modify Documents

var doc: Document = ["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 Document conforms to Collection, so useful methods from Sequence and Collection are all available. However, runtime guarantees are not yet met for many of these methods.

Usage With Kitura, Vapor, and Perfect

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

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

Development Instructions

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

Github

link
Stars: 160

Dependencies

Used By

Total: 0

Releases

MongoSwift 1.0.0-rc0 - 2020-02-27 16:28:06

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

MongoSwift 0.2.0 - 2019-12-18 20:45:28

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

- 2019-06-04 23:20:56

This release includes a couple of small fixes to correct inadvertent backwards-breaking changes introduced in 0.1.1.

MongoSwift 0.1.1 - 2019-06-04 18:23:55

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

MongoSwift 0.1.0 - 2019-04-18 21:21:08

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