MongoClient
public class MongoClient
extension MongoClient: Equatable
A MongoDB Client providing an asynchronous, SwiftNIO-based API.
-
Encoder whose options are inherited by databases derived from this client.
Declaration
Swift
public let encoder: BSONEncoder
-
Decoder whose options are inherited by databases derived from this client.
Declaration
Swift
public let decoder: BSONDecoder
-
The read concern set on this client, or nil if one is not set.
Declaration
Swift
public let readConcern: ReadConcern?
-
The
ReadPreference
set on this client.Declaration
Swift
public let readPreference: ReadPreference
-
The write concern set on this client, or nil if one is not set.
Declaration
Swift
public let writeConcern: WriteConcern?
-
Create a new client for a MongoDB deployment. For options that included in both the
MongoConnectionString
and theMongoClientOptions
struct, the final value is set in descending order of priority: the value specified inMongoClientOptions
(if non-nil), the value specified in the URI, or the default value if both are unset.Throws
Throws:
- A
MongoError.InvalidArgumentError
if the connection string passed in is improperly formatted.
Declaration
Swift
public init( _ connectionString: MongoConnectionString, using eventLoopGroup: EventLoopGroup, options: MongoClientOptions? = nil ) throws
Parameters
connectionString
the
MongoConnectionString
to connect to.eventLoopGroup
A SwiftNIO
EventLoopGroup
which the client will use for executing operations. It is the user’s responsibility to ensure the group remains active for as long as the client does, and to ensure the group is properly shut down when it is no longer in use.options
optional
MongoClientOptions
to use for this client. - A
-
Create a new client for a MongoDB deployment. For options that included in both the connection string URI and the
MongoClientOptions
struct, the final value is set in descending order of priority: the value specified inMongoClientOptions
(if non-nil), the value specified in the URI, or the default value if both are unset.Throws
Throws:
- A
MongoError.InvalidArgumentError
if the connection string passed in is improperly formatted.
Declaration
Swift
public convenience init( _ connectionString: String = "mongodb://localhost:27017", using eventLoopGroup: EventLoopGroup, options: MongoClientOptions? = nil ) throws
Parameters
connectionString
the connection string to connect to.
eventLoopGroup
A SwiftNIO
EventLoopGroup
which the client will use for executing operations. It is the user’s responsibility to ensure the group remains active for as long as the client does, and to ensure the group is properly shut down when it is no longer in use.options
optional
MongoClientOptions
to use for this client. - A
-
Closes this
MongoClient
, closing all connections to the server and cleaning up internal state.Call this method exactly once when you are finished using the client. You must ensure that all operations using the client have completed before calling this.
The returned future will not be fulfilled until all cursors and change streams created from this client have been been killed, and all sessions created from this client have been ended.
The returned future must be fulfilled before the
EventLoopGroup
provided to this client’s constructor is shut down.Declaration
Swift
public func close() -> EventLoopFuture<Void>
-
Shuts this
MongoClient
down in a blocking fashion, closing all connections to the server and cleaning up internal state.Call this method exactly once when you are finished using the client. You must ensure that all operations using the client have completed before calling this. This method will block until all cursors and change streams created from this client have been killed, and all sessions created from this client have been ended.
This method must complete before the
EventLoopGroup
provided to this client’s constructor is shut down.Declaration
Swift
public func syncClose() throws
-
Starts a new
ClientSession
with the provided options.This session must be explicitly as an argument to each command that should be executed as part of the session.
ClientSession
s are not thread safe so you must ensure the returned session is not used concurrently for multiple operations.When you are done using this session, you must call
ClientSession.end()
on it, unless if you are on a platform where structured concurrency is available, in which case the session will be ended automatically when the object is deinitialized. In that case, you must make sure to maintain a reference to this object until all operations using it have completed.Declaration
Swift
public func startSession(options: ClientSessionOptions? = nil) -> ClientSession
-
Starts a new
ClientSession
with the provided options and passes it to the provided closure. The session must be explicitly passed as an argument to each command within the closure that should be executed as part of the session.The session is only valid within the body of the closure and will be ended after the body completes.
ClientSession
s are not thread safe so you must ensure the session is not used concurrently for multiple operations.Declaration
Swift
public func withSession<T>( options: ClientSessionOptions? = nil, _ sessionBody: (ClientSession) throws -> EventLoopFuture<T> ) -> EventLoopFuture<T>
Parameters
options
Options to use when creating the session.
sessionBody
A closure which takes in a
ClientSession
and returns anEventLoopFuture<T>
.Return Value
An
EventLoopFuture<T>
, the return value of the user-provided closure.If the future fails, the error is likely one of the following:
CompatibilityError
if the deployment does not support sessions.MongoError.LogicError
if this client has already been closed.
-
Retrieves a list of databases in this client’s MongoDB deployment.
Declaration
Swift
public func listDatabases( _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture<[DatabaseSpecification]>
Parameters
filter
Optional
BSONDocument
specifying a filter that the listed databases must pass. This filter can be based on the “name”, “sizeOnDisk”, “empty”, or “shards” fields of the output.options
Optional
ListDatabasesOptions
specifying options for listing databases.session
Optional
ClientSession
to use when executing this command.Return Value
An
EventLoopFuture<[DatabaseSpecification]>
. On success, the future contains an array of the specifications of databases matching the provided criteria.If the future fails, the error is likely one of the following:
MongoError.LogicError
if the provided session is inactive.MongoError.LogicError
if this client has already been closed.EncodingError
if an error is encountered while encoding the options to BSON.MongoError.CommandError
if options.authorizedDatabases is false and the user does not have listDatabases permissions.
-
Get a list of
MongoDatabase
s corresponding to the databases in this client’s MongoDB deployment.Declaration
Swift
public func listMongoDatabases( _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture<[MongoDatabase]>
Parameters
filter
Optional
BSONDocument
specifying a filter on the names of the returned databases.options
Optional
ListDatabasesOptions
specifying options for listing databases.session
Optional
ClientSession
to use when executing this commandReturn Value
An
EventLoopFuture<[MongoDatabase]>
. On success, the future contains an array ofMongoDatabase
s that match the provided filter.If the future fails, the error is likely one of the following:
MongoError.LogicError
if the provided session is inactive.MongoError.LogicError
if this client has already been closed.MongoError.CommandError
if options.authorizedDatabases is false and the user does not have listDatabases permissions.
-
Get the names of databases in this client’s MongoDB deployment.
Declaration
Swift
public func listDatabaseNames( _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture<[String]>
Parameters
filter
Optional
BSONDocument
specifying a filter on the names of the returned databases.options
Optional
ListDatabasesOptions
specifying options for listing databases.session
Optional
ClientSession
to use when executing this commandReturn Value
An
EventLoopFuture<[String]>
. On success, the future contains an array of names of databases that match the provided filter.If the future fails, the error is likely one of the following:
MongoError.LogicError
if the provided session is inactive.MongoError.LogicError
if this client has already been closed.MongoError.CommandError
if options.authorizedDatabases is false and the user does not have listDatabases permissions.
-
Gets a
MongoDatabase
instance for the given database name. If an option is not specified in the optionalMongoDatabaseOptions
param, the database will inherit the value from the parent client or the default if the client’s option is not set. To override an option inherited from the client (e.g. a read concern) with the default value, it must be explicitly specified in the options param (e.g. ReadConcern.serverDefault, not nil).Declaration
Swift
public func db(_ name: String, options: MongoDatabaseOptions? = nil) -> MongoDatabase
Parameters
name
the name of the database to retrieve
options
Optional
MongoDatabaseOptions
to use for the retrieved databaseReturn Value
a
MongoDatabase
corresponding to the provided database name. -
Starts a
ChangeStream
on aMongoClient
. Allows the client to observe all changes in a cluster - excluding system collections and the “config”, “local”, and “admin” databases.Warning
If the returned change stream is alive when it goes out of scope, it will leak resources. To ensure the change stream is dead before it leaves scope, invoke
ChangeStream.kill(...)
on it.See also
SeeAlso:
Note
Supported in MongoDB version 4.0+ only.
Declaration
Swift
public func watch( _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture<ChangeStream<ChangeStreamEvent<BSONDocument>>>
Parameters
pipeline
An array of aggregation pipeline stages to apply to the events returned by the change stream.
options
An optional
ChangeStreamOptions
to use when constructing the change stream.session
An optional
ClientSession
to use with this change stream.Return Value
An
EventLoopFuture<ChangeStream>
. On success, contains aChangeStream
watching all collections in this deployment.If the future fails, the error is likely one of the following:
MongoError.CommandError
if an error occurs on the server while creating the change stream.MongoError.InvalidArgumentError
if the options passed formed an invalid combination.MongoError.InvalidArgumentError
if the_id
field is projected out of the change stream documents by the pipeline.
-
Starts a
ChangeStream
on aMongoClient
. Allows the client to observe all changes in a cluster - excluding system collections and the “config”, “local”, and “admin” databases. Associates the specifiedCodable
typeT
with thefullDocument
field in theChangeStreamEvent
s emitted by the returnedChangeStream
.Warning
If the returned change stream is alive when it goes out of scope, it will leak resources. To ensure the change stream is dead before it leaves scope, invoke
ChangeStream.kill(...)
on it.See also
SeeAlso:
Note
Supported in MongoDB version 4.0+ only.
Declaration
Swift
public func watch<FullDocType: Codable>( _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withFullDocumentType _: FullDocType.Type ) -> EventLoopFuture<ChangeStream<ChangeStreamEvent<FullDocType>>>
Parameters
pipeline
An array of aggregation pipeline stages to apply to the events returned by the change stream.
options
An optional
ChangeStreamOptions
to use when constructing the change stream.session
An optional
ClientSession
to use with this change stream.withFullDocumentType
The type that the
fullDocument
field of the emittedChangeStreamEvent
s will be decoded to.Return Value
An
EventLoopFuture<ChangeStream>
. On success, contains aChangeStream
watching all collections in this deployment.If the future fails, the error is likely one of the following:
MongoError.CommandError
if an error occurs on the server while creating the change stream.MongoError.InvalidArgumentError
if the options passed formed an invalid combination.MongoError.InvalidArgumentError
if the_id
field is projected out of the change stream documents by the pipeline.
-
Starts a
ChangeStream
on aMongoClient
. Allows the client to observe all changes in a cluster - excluding system collections and the “config”, “local”, and “admin” databases. Associates the specifiedCodable
typeT
with the returnedChangeStream
.Warning
If the returned change stream is alive when it goes out of scope, it will leak resources. To ensure the change stream is dead before it leaves scope, invoke
ChangeStream.kill(...)
on it.See also
SeeAlso:
Note
Supported in MongoDB version 4.0+ only.
Declaration
Swift
public func watch<EventType: Codable>( _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withEventType _: EventType.Type ) -> EventLoopFuture<ChangeStream<EventType>>
Parameters
pipeline
An array of aggregation pipeline stages to apply to the events returned by the change stream.
options
An optional
ChangeStreamOptions
to use when constructing the change stream.session
An optional
ClientSession
to use with this change stream.withEventType
The type that the entire change stream response will be decoded to and that will be returned when iterating through the change stream.
Return Value
An
EventLoopFuture<ChangeStream>
. On success, contains aChangeStream
watching all collections in this deployment.If the future fails, the error is likely one of the following:
MongoError.CommandError
if an error occurs on the server while creating the change stream.MongoError.InvalidArgumentError
if the options passed formed an invalid combination.MongoError.InvalidArgumentError
if the_id
field is projected out of the change stream documents by the pipeline.
-
Returns an
EventLoopBoundMongoClient
, a wrapper around thisMongoClient
that will returnEventLoopFuture
s on the specifiedEventLoop
.Note
This
MongoClient
must be kept alive in order to use theEventLoopBoundMongoClient
.Declaration
Swift
public func bound(to eventLoop: EventLoop) -> EventLoopBoundMongoClient
Parameters
eventLoop
An
EventLoop
which the returnedEventLoopBoundMongoClient
will be bound to.Return Value
An
EventLoopBoundMongoClient
bound to the specifiedEventLoop
. -
Attach a
CommandEventHandler
that will receiveCommandEvent
s emitted by this client.Note: the client stores a weak reference to this handler, so it must be kept alive separately in order for it to continue to receive events.
Declaration
Swift
public func addCommandEventHandler<T>(_ handler: T) where T : CommandEventHandler
-
Attach a callback that will receive
CommandEvent
s emitted by this client.Note: if the provided callback captures this client, it must do so weakly. Otherwise, it will constitute a strong reference cycle and potentially result in memory leaks.
Declaration
Swift
public func addCommandEventHandler(_ handlerFunc: @escaping (CommandEvent) -> Void)
-
Attach an
SDAMEventHandler
that will receiveCommandEvent
s emitted by this client.Note: the client stores a weak reference to this handler, so it must be kept alive separately in order for it to continue to receive events.
Declaration
Swift
public func addSDAMEventHandler<T>(_ handler: T) where T : SDAMEventHandler
-
Attach a callback that will receive
SDAMEvent
s emitted by this client.Note: if the provided callback captures this client, it must do so weakly. Otherwise, it will constitute a strong reference cycle and potentially result in memory leaks.
Declaration
Swift
public func addSDAMEventHandler(_ handlerFunc: @escaping (SDAMEvent) -> Void)
-
close()
AsynchronousCloses this
MongoClient
, closing all connections to the server and cleaning up internal state.Call this method exactly once when you are finished using the client.
This function will not complete until all cursors and change streams created from this client have been been killed, and all sessions created from this client have been ended.
You must
await
the result of this method before shutting down theEventLoopGroup
provided to this client’s constructor.Declaration
Swift
public func close() async throws
-
withSession(options:
Asynchronous_: ) Starts a new
ClientSession
with the provided options and passes it to the provided closure. The session must be explicitly passed as an argument to each command within the closure that should be executed as part of the session.The session is only valid within the body of the closure and will be ended after the body completes.
ClientSession
s are not thread safe so you must ensure the session is not used concurrently for multiple operations.Throws
Throws:
RuntimeError.CompatibilityError
if the deployment does not support sessions.
Declaration
Swift
public func withSession<T>( options: ClientSessionOptions? = nil, _ sessionBody: (ClientSession) async throws -> T ) async throws -> T
Parameters
options
Options to use when creating the session.
sessionBody
An
async
closure which takes in aClientSession
and returns aT
.Return Value
A
T
, the return value of the user-provided closure. -
listDatabases(_:
Asynchronousoptions: session: ) Run the
listDatabases
command.Throws
Throws:
MongoError.LogicError
if the provided session is inactive.EncodingError
if an error is encountered while encoding the options to BSON.MongoError.CommandError
if options.authorizedDatabases is false and the user does not have listDatabases permissions.
Declaration
Swift
public func listDatabases( _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) async throws -> [DatabaseSpecification]
Parameters
filter
Optional
BSONDocument
specifying a filter that the listed databases must pass. This filter can be based on the “name”, “sizeOnDisk”, “empty”, or “shards” fields of the output.options
Optional
ListDatabasesOptions
specifying options for listing databases.session
Optional
ClientSession
to use when executing this command.Return Value
A
[DatabaseSpecification]
containing the databases matching provided criteria. -
listMongoDatabases(_:
Asynchronousoptions: session: ) Get a list of
MongoDatabase
s.Throws
Throws:
MongoError.LogicError
if the provided session is inactive.MongoError.CommandError
if options.authorizedDatabases is false and the user does not have listDatabases permissions.
Declaration
Swift
public func listMongoDatabases( _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) async throws -> [MongoDatabase]
Parameters
filter
Optional
BSONDocument
specifying a filter on the names of the returned databases.options
Optional
ListDatabasesOptions
specifying options for listing databases.session
Optional
ClientSession
to use when executing this command.Return Value
An Array of
MongoDatabase
s that match the provided filter. -
listDatabaseNames(_:
Asynchronousoptions: session: ) Get a list of names of databases.
Throws
Throws:
MongoError.LogicError
if the provided session is inactive.MongoError.CommandError
if options.authorizedDatabases is false and the user does not have listDatabases permissions.
Declaration
Swift
public func listDatabaseNames( _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) async throws -> [String]
Parameters
filter
Optional
BSONDocument
specifying a filter on the names of the returned databases.options
Optional
ListDatabasesOptions
specifying options for listing databases.session
Optional
ClientSession
to use when executing this command.Return Value
A
[String]
containing names of databases that match the provided filter. -
watch(_:
Asynchronousoptions: session: ) Starts a
ChangeStream
on aMongoClient
. Allows the client to observe all changes in a cluster - excluding system collections and the “config”, “local”, and “admin” databases.Throws
Throws:
MongoError.CommandError
if an error occurs on the server while creating the change stream.MongoError.InvalidArgumentError
if the options passed formed an invalid combination.MongoError.InvalidArgumentError
if the_id
field is projected out of the change stream documents by the pipeline.
See also
SeeAlso:
Note
Supported in MongoDB version 4.0+ only.
Declaration
Swift
public func watch( _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil ) async throws -> ChangeStream<ChangeStreamEvent<BSONDocument>>
Parameters
pipeline
An array of aggregation pipeline stages to apply to the events returned by the change stream.
options
An optional
ChangeStreamOptions
to use when constructing the change stream.session
An optional
ClientSession
to use with this change stream.Return Value
a
ChangeStream
on all collections in all databases in a cluster. -
watch(_:
Asynchronousoptions: session: withFullDocumentType: ) Starts a
ChangeStream
on aMongoClient
. Allows the client to observe all changes in a cluster - excluding system collections and the “config”, “local”, and “admin” databases. Associates the specifiedCodable
typeT
with thefullDocument
field in theChangeStreamEvent
s emitted by the returnedChangeStream
.Throws
Throws:
MongoError.CommandError
if an error occurs on the server while creating the change stream.MongoError.InvalidArgumentError
if the options passed formed an invalid combination.MongoError.InvalidArgumentError
if the_id
field is projected out of the change stream documents by the pipeline.
See also
SeeAlso:
Note
Supported in MongoDB version 4.0+ only.
Declaration
Swift
public func watch<FullDocType: Codable>( _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withFullDocumentType _: FullDocType.Type ) async throws -> ChangeStream<ChangeStreamEvent<FullDocType>>
Parameters
pipeline
An array of aggregation pipeline stages to apply to the events returned by the change stream.
options
An optional
ChangeStreamOptions
to use when constructing the change stream.session
An optional
ClientSession
to use with this change stream.withFullDocumentType
The type that the
fullDocument
field of the emittedChangeStreamEvent
s will be decoded to.Return Value
A
ChangeStream
on all collections in all databases in a cluster. -
watch(_:
Asynchronousoptions: session: withEventType: ) Starts a
ChangeStream
on aMongoClient
. Allows the client to observe all changes in a cluster - excluding system collections and the “config”, “local”, and “admin” databases. Associates the specifiedCodable
typeT
with the returnedChangeStream
.Throws
Throws:
MongoError.CommandError
if an error occurs on the server while creating the change stream.MongoError.InvalidArgumentError
if the options passed formed an invalid combination.MongoError.InvalidArgumentError
if the_id
field is projected out of the change stream documents by the pipeline.
See also
SeeAlso:
Note
Supported in MongoDB version 4.0+ only.
Declaration
Swift
public func watch<EventType: Codable>( _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withEventType _: EventType.Type ) async throws -> ChangeStream<EventType>
Parameters
pipeline
An array of aggregation pipeline stages to apply to the events returned by the change stream.
options
An optional
ChangeStreamOptions
to use when constructing the change stream.session
An optional
ClientSession
to use with this change stream.withEventType
The type that the entire change stream response will be decoded to and that will be returned when iterating through the change stream.
Return Value
A
ChangeStream
on all collections in all databases in a cluster. -
Declaration
Swift
public static func == (lhs: MongoClient, rhs: MongoClient) -> Bool