The MongoClient class is where the initial connection to the MongoDB server is defined.
Create a new Mongo client connection:
let client = try! MongoClient(uri: "mongodb://localhost")
Once the connection is established and the database and collections have been defined, set the connection to close once completed using defer
. This is done in reverse order: close collections, then databases, and then finally the client connection.
defer {
collection.close()
db.close()
client.close()
}
getDatabase
returns the specified MongoDatabase using the current connection.
let db = client.getDatabase(
databaseName: <String>
)
- databaseName: String name of database to be used
getCollection
returns the specified MongoCollection from the specified database using the current connection.
let collection = client.getCollection(
databaseName: <String>,
collectionName: <String>
)
- databaseName: String name of database to be used
- collectionName: String name of collection to be retrieved
serverStatus
returns: a Result object representing the server status.
let status = client.serverStatus()
Use databaseNames
to build a string array of current database names:
let dbnames = client.databaseNames()