Module: Perfect-MongoDB
enum BSONError: Error
BSON error enum
case syntaxError(String)
The JSON data was malformed.
class BSON: CustomStringConvertible
BSON class
var description: String
Return JSON representation of current BSON contents as a String
func init()
Allocates a new doc structure. Call the various append() functions to add fields to the bson. You can iterate the doc at any time using a bson_iter_t and bson_iter_init().
func init(bytes: [UInt8])
Creates a new doc structure using the data provided. bytes should contain bytes that can be copied into the new doc structure.
*
*- parameter bytes: A byte array containing a serialized bson document.
func init(json: String) throws
Creates a new doc structure using the data provided. json should contain bytes that can be copied into the new doc structure.

- parameter json: A string containing a json data.
func init(document: BSON)
Creates a new doc by copying the provided bson doc.

- parameter document: An existing bson document.
func close()
close, destroy and release the current BSON document
var asString: String
Creates a new string containing current document in extended JSON format.

See http://docs.mongodb.org/manual/reference/mongodb-extended-json/ for
more information on extended JSON.

- returns: String
var asArrayString: String
like asString() but for outermost arrays.
var asBytes: [UInt8]
asBytes:

- returns: A byte array from current BSON document
func append(key k: String, document: BSON) -> Bool
Appends a new field to self.doc of the type BSON_TYPE_DOCUMENT. The documents contents will be copied into self.doc.

- parameter key: The key for the field.
- parameter document: Existing BSON document.
- returns: true if successful; false if append would overflow max size.
func append(key k: String) -> Bool
Appends a new field to self.doc with NULL for the value.

- parameter key: The key for the field.

- returns: true if successful; false if append would overflow max size.
func append(key k: String, oid: bson_oid_t) -> Bool
Appends a new field to the self.doc of type BSON_TYPE_OID using the contents of
oid.

- parameter key: The key for the field.
- parameter oid: bson_oid_t.

- returns: true if successful; false if append would overflow max size.
func append(key k: String, int: Int) -> Bool
Appends a new field of type BSON_TYPE_INT64 to self.doc .

- parameter key: The key for the field.
- parameter int: The Int 64-bit integer value.


- returns: true if successful; false if append would overflow max size.
func append(key k: String, int32: Int32) -> Bool
Appends a new field of type BSON_TYPE_INT32 to self.doc .

- parameter key: The key for the field.
- parameter int32: The Int32 32-bit integer value.


- returns: true if successful; false if append would overflow max size.
func append(key k: String, dateTime: Int64) -> Bool
Appends a new field to self.doc of type BSON_TYPE_DATE_TIME.

- parameter key: The key for the field.
- parameter dateTime: The number of milliseconds elapsed since UNIX epoch.


- returns: true if sucessful; otherwise false.
func append(key k: String, time: time_t) -> Bool
Appends a BSON_TYPE_DATE_TIME field to self.doc using the time_t @value for the
number of seconds since UNIX epoch in UTC.

- parameter key: The key for the field.
- parameter time: A time_t.


- returns: true if successful; false if append would overflow max size.
func append(key k: String, double: Double) -> Bool
Appends a new field to self.doc of the type BSON_TYPE_DOUBLE.

- parameter key: The key for the field.
- parameter double: The double to be appended

- returns: true if successful; false if append would overflow max size.
func append(key k: String, bool: Bool) -> Bool
Appends a new field to self.doc of type BSON_TYPE_BOOL.

- parameter key: The key for the field.
- parameter bool: The boolean value.

- returns: true if successful; false if append would overflow max size.
func append(key k: String, string: String) -> Bool
Appends a new field to self.doc using @key as the key and @string as the UTF-8
encoded value.

- parameter key: The key for the field.
- parameter string: A UTF-8 encoded string.

- returns: true if successful; false if append would overflow max size.
func append(key k: String, bytes: [UInt8]) -> Bool
Appends a bytes buffer to the BSON document.

- parameter key: The key for the field.
- parameter bytes: The bytes to append

- returns: true if successful; false if append would overflow max size.
func append(key k: String, regex: String, options: String) -> Bool
Appends a new field to self.doc of type BSON_TYPE_REGEX. @regex should
be the regex string. @options should contain the options for the regex.

Valid options for @options are:

'i' for case-insensitive.
'm' for multiple matching.
'x' for verbose mode.
'l' to make \w and \W locale dependent.
's' for dotall mode ('.' matches everything)
'u' to make \w and \W match unicode.

For more information on what comprimises a BSON regex, see bsonspec.org.

- parameter key: The key of the field.
- parameter regex: The regex to append to the bson.
- parameter options: Options for @regex.

- returns: true if successful; false if append would overflow max size.
func countKeys() -> Int
Counts the number of elements found in self.doc.
- returns: Int value of keys count
func hasField(key k: String) -> Bool
Checks to see if self.doc contains a field named @key.

This function is case-sensitive.

- parameter key: The key to lookup.

- returns: true if @key exists in self.doc; otherwise false.
func appendArrayBegin(key k: String, child: BSON) -> Bool
Appends a new field named key to self.doc, the field is, however,
incomplete. @child will be initialized so that you may add fields to the
child array. Child will use a memory buffer owned by self.doc and
therefore grow the parent buffer as additional space is used. This allows
a single malloc'd buffer to be used when building arrays which can help
reduce memory fragmentation.

The type of @child will be BSON_TYPE_ARRAY and therefore the keys inside
of it MUST be "0", "1", etc.

- parameter key: The key for the field.
- parameter child: A location to an uninitialized bson_t.

- returns: true if successful; false if append would overflow max size.
func appendArrayEnd(child: BSON) -> Bool
Finishes the appending of an array to self.doc. child is considered
disposed after this call and should not be used any further.

- parameter child: A bson document supplied to appendArrayBegin().

- returns: true if successful; false if append would overflow max size.
func appendArray(key k: String, array: BSON) -> Bool
Appends a BSON array to self.doc. BSON arrays are like documents where the
key is the string version of the index. For example, the first item of the
array would have the key "0". The second item would have the index "1".

- parameter key: The key for the field.
- parameter array: A bson document containing the array.

- returns: true if successful; false if append would overflow max size.
func concat(src: BSON) -> Bool
Concatenate src with self.doc

- parameter src: BSON doc to be concatenated.

- returns: true if successful; false if append would overflow max size.
func append(key: String = "_id", oid: OID) -> Bool
Add the OID with the given key.
Key defaults to "_id"
func <(lhs: BSON, rhs: BSON) -> Bool
compare two BSON documents for sort priority

- returns: true if lhs sorts above rhs, false otherwise.
extension BSON
struct BSONValue
A BSONValue produced by iterating a document's keys.
struct Iterator
An iterator for BSON keys and values.
var currentType: BSONType?
The type of the current value.
var currentKey: String?
The key for the current value.
var currentChildIterator: Iterator?
If the current value is an narray or document, this returns an iterator
which can be used to walk it.
var currentValue: BSONValue?
The BSON value for the current element.
func mutating func next() -> Bool
Advance to the next element.
Note that all iterations must begin by first calling next.
func mutating func find(key: String, withCase: Bool = true) -> Bool
Located the key and advance the iterator to point at it.
If `withCase` is false then the search will be case in-sensitive.
func mutating func findDescendant(key: String) -> Iterator?
Follow standard MongoDB dot notation to recurse into subdocuments.
Returns nil if the descendant is not found.
func iterator() -> Iterator?
Return a new iterator for this document.
enum MongoClientError: Error
ErrorType for MongoClient error reporting
case initError(String)
returns error string
class MongoClient
typealias typealias Result = MongoResult
Result Status enum for a MongoDB event
func init(uri: String) throws
Create new Mongo Client connection

- throws: MongoClientError "Could not parse URI" if nil response
func close()
terminate current Mongo Client connection
func getCollection(databaseName: String, collectionName: String) -> MongoCollection
Return the specified MongoCollection from the specified database using current connection

- parameter databaseName: String name of database to be used
- parameter collectionName: String name of collection to be retrieved

- returns: MongoCollection from specified database
func getDatabase(name databaseName: String) -> MongoDatabase
Return the named database as a MongoDatabase object

- parameter name: String name of database to be retrieved
- returns: a MongoDatabase object
func serverStatus() -> Result
Get current Mongo server status

- returns: a Result object representing the server status
func databaseNames() -> [String]
Build String Array of current database names

- returns: [String] of current database names
class MongoCollection
The MongoCollection class
typealias typealias Result = MongoResult
Result Status enum for a MongoDB event
func init(client: MongoClient, databaseName: String, collectionName: String)
obtain access to a specified database and collection using the MongoClient

- parameter client: the MongoClient to be used
- parameter databaseName: String database name
- parameter collectionName: String collection name
func close()
close connection to the current collection
func insert(document: BSON, flag: MongoInsertFlag = .none) -> Result
Insert **document** into the current collection returning a result status

- parameter document: BSON document to be inserted
- parameter flag: Optional MongoInsertFlag defaults to .None

- returns: Result object with status of insert
func insert(documents: [BSON]) -> Result
Insert **documents** into the current collection returning a result status

- parameter documents: BSON documents to be inserted

- returns: Result object with status of insert
func update(selector: BSON, update: BSON, flag: MongoUpdateFlag = .none) -> Result
Update the document found using **selector** with the **update** document returning a result status

- parameter selector: BSON document with selection criteria
- parameter update: BSON document to be used to update
- parameter flag: Optional MongoUpdateFlag defaults to .None

- returns: Result object with status of update
func update(updates: [(selector: BSON, update: BSON)]) -> Result
* Update the documents and return a result status
*
* - parameter updates: Tuple of (selector: BSON, update: BSON)
*
* - returns: Result object with status of update
*
* How to use it!
*
* var updates: [(selector: BSON, update: BSON)] = []
* guard var users = collection.find(query: BSON()) else {
* response.status = HTTPResponseStatus.custom(code: 404, message: "Collection users cannot perform find().")
* response.completed()
* return
}
* for user in users {
* let oldBson = BSON()
* oldBson.append(key: "_id", oid: user.oid!)
* let innerBson = BSON()
* innerBson.append(key: "firstname", string: "Ciccio")
* let newdBson = BSON()
* newdBson.append(key: "$set", document: innerBson)
* updates.append((selector: oldBson, update: newdBson))
* }
* if case .error = collection.update(updates: updates) {
* response.status = HTTPResponseStatus.custom(code: 404, message: "Collection users cannot perform multiple update().")
* response.completed()
* return
}
func remove(selector sel: BSON, flag: MongoRemoveFlag = .none) -> Result
Remove the document found using **selector** returning a result status

- parameter selector: BSON document with selection criteria
- parameter flag: Optional MongoRemoveFlag defaults to .None

- returns: Result object with status of removal
func save(document doc: BSON) -> Result
Updates **document** returning a result status

- parameter document: BSON document to be saved

- returns: Result object with status of save
func rename(newDbName: String, newCollectionName: String, dropExisting: Bool) -> Result
Renames the collection using **newDbName** and **newCollectionName**, with option to drop existing collection immediately instead of after the move, returning a result status

- parameter newDbName: String name for db after move
- parameter newCollectionName: String name for collection after move
- parameter dropExisting: Bool option to drop existing collection immediately instead of after move

- returns: Result object with status of renaming
func name() -> String
The collection name as a String

- returns: String the name of the current collection
func validate(full: Bool = false) -> Result
Validates a collection. The method scans a collection’s data structures for correctness and returns a single document that describes the relationship between the logical collection and the physical representation of the data.

- parameter full: Optional. Specify true to enable a full validation and to return full statistics. MongoDB disables full validation by default because it is a potentially resource-intensive operation.

- returns: BSON document describing the relationship between the collection and its physical representation
func stats(options: BSON) -> Result
Returns statistics about the collection formatted according to the options document.

- parameter options: a BSON document defining the format of return.
- **The options document can contain the following fields and values**:

- **scale**: *number*, Optional. The scale used in the output to display the sizes of items. By default, output displays sizes in bytes. To display kilobytes rather than bytes, specify a scale value of 1024.
- **indexDetails**: *boolean*, Optional. If true, **stats()** returns index details in addition to the collection stats. Only works for WiredTiger storage engine. Defaults to false.
- **indexDetailsKey**: *document*, Optional. If **indexDetails** is true, you can use **indexDetailsKey** to filter index details by specifying the index key specification. Only the index that exactly matches **indexDetailsKey** will be returned. If no match is found, **indexDetails** will display statistics for all indexes.
- **indexDetailsName**: *string*, Optional. If **indexDetails** is true, you can use **indexDetailsName** to filter index details by specifying the index name. Only the index name that exactly matches **indexDetailsName** will be returned. If no match is found, **indexDetails** will display statistics for all indexes.

- returns: BSON document with formatted statistics or Results error document
func find(query: BSON = BSON(), fields: BSON? = nil, flags: MongoQueryFlag = MongoQueryFlag.none, skip: Int = 0, limit: Int = 0, batchSize: Int = 0) -> MongoCursor?
Selects documents in a collection and returns a cursor to the selected documents.

- parameter query: Specifies selection filter using query operators. To return all documents in a collection, omit this- Parameter or pass an empty document ({}).
- parameter fields: Optional. Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, omit this parameter.
- parameter flags: Optional. set queryFlags for the current search
- parameter skip: Optional. Skip the supplied number of records.
- parameter limit: Optional. return no more than the supplied number of records.
- parameter batchSize: Optional. Change number of automatically iterated documents.

- returns: A cursor to the documents that match the query criteria. When the find() method “returns documents,” the method is actually returning a cursor to the documents.
func createIndex(keys: BSON, options: MongoIndexOptions) -> Result
Creates indexes on collections.

- parameter keys: A document that conains the field and value pairs where the field is the index key and the value describes the type of index for that field. For an ascending index on a field, specify a value of 1; for descending index, specify a value of -1.
- parameter options: Optional. A document that contains a set of options that controls the creation of the index. see MongoIndexOptions for details.

- returns: a Result status
func dropIndex(name: String) -> Result
Drops or removes the specified index from a collection.

- parameter index: Specifies the index to drop, either by name or by the index specification document.

- returns: a Result status
func drop() -> Result
Removes a collection from the database. The method also removes any indexes associated with the dropped collection.

- returns: a Result status
func count(query: BSON, flags: MongoQueryFlag = MongoQueryFlag.none, skip: Int = 0, limit: Int = 0, batchSize: Int = 0) -> Result
The count of documents that would match a find() query.

- parameter query: The query selection criteria.
- parameter flags: Optional. set queryFlags for the current search
- parameter skip: Optional. Skip the supplied number of records.
- parameter limit: Optional. return no more than the supplied number of records.
- parameter batchSize: Optional. Change number of automatically iterated documents.

- returns: the count of documents that would match a find() query. The count() method does not perform the find() operation but instead counts and returns the number of results that match a query.
func findAndModify(query: BSON?, sort: BSON?, update: BSON?, fields: BSON?, remove: Bool, upsert: Bool, new: Bool) -> Result
Modifies and returns a single document.

- parameter query: Optional. The selection criteria for the modification. The query field employs the same query selectors as used in the db.collection.find() method. Although the query may match multiple documents, findAndModify() will only select one document to modify.
- parameter sort: Optional. Determines which document the operation modifies if the query selects multiple documents. findAndModify() modifies the first document in the sort order specified by this argument.
- parameter update: Must specify either the remove or the update field. Performs an update of the selected document. The update field employs the same update operators or field: value specifications to modify the selected document.
- parameter fields: Optional. A subset of fields to return. The fields document specifies an inclusion of a field with 1, as in: fields: { <field1>: 1, <field2>: 1, ... }.
- parameter remove: Must specify either the remove or the update field. Removes the document specified in the query field. Set this to true to remove the selected document . The default is false.
- parameter upsert: Optional. Used in conjunction with the update field. When true, findAndModify() creates a new document if no document matches the query, or if documents match the query, findAndModify() performs an update. To avoid multiple upserts, ensure that the query fields are uniquely indexed. The default is false.
- parameter new: Optional. When true, returns the modified document rather than the original. The findAndModify() method ignores the new option for remove operations. The default is false.

- returns: Modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.
func getLastError() -> BSON
A BSON document with description of last transaction status

- returns: BSON document with description of last transaction status
func distinct(key: String, query: BSON? = nil, readConcern: BSON? = nil, flags: MongoQueryFlag = MongoQueryFlag.none, skip: Int = 0, limit: Int = 0, batchSize: Int = 0) -> BSON?
Finds the distinct values and returns a cursor for a specified field across a single collection.

- parameter key: The field for which to return distinct values.
- parameter query: Optional. A query that specifies the documents from which to retrieve the distinct values.
- parameter readConcern: Optional. Specifies a level of isolation for read operations.
- parameter flags: Optional. set queryFlags for the current search
- parameter skip: Optional. Skip the supplied number of records.
- parameter limit: Optional. return no more than the supplied number of records.
- parameter batchSize: Optional. Change number of automatically iterated documents.

- returns: BSON document with distinct document.
func command(command: BSON, fields: BSON? = nil, flags: MongoQueryFlag = MongoQueryFlag.none, skip: Int = 0, limit: Int = 0, batchSize: Int = 0) -> MongoCursor?
Runs specified database command.

- parameter command: Database command.
- parameter fields: Optional. Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, omit this parameter.
- parameter flags: Optional. set queryFlags for the current search
- parameter skip: Optional. Skip the supplied number of records.
- parameter limit: Optional. return no more than the supplied number of records.
- parameter batchSize: Optional. Change number of automatically iterated documents.

- returns: A cursor to the command execution result documents.
class MongoClientPool
Allows connection pooling. This class is thread-safe.
func init(uri: String)
create new ClientPool with provided String uri

- parameter uri: String uri to connect client pool
func tryPopClient() -> MongoClient?
Try to pop a client connection from the connection pool.

- returns: nil if no client connection is currently queued for reuse.
func popClient() -> MongoClient
Pop a client connection from the connection pool.

- returns: MongoClient from connection pool
func pushClient(_ client: MongoClient)
Pushes back popped client connection.

- parameter client: MongoClient to be pushed back into pool
func executeBlock(_ block: (_ client: MongoClient) -> Void)
Automatically pops a client, makes it available within the block and pushes it back.

- parameter block: block to be executed with popped client
class MongoCursor: Sequence, IteratorProtocol
The Mongo Cursor interface
func close()
Close and destroy current cursor
func next() -> BSON?
- returns: next document if available, else nil
class MongoDatabase
MongoDatabase is an open-source document database that provides high performance, high availability, and automatic scaling.
func init(client: MongoClient, databaseName: String)
Get reference to named database using provided MongoClient instance

- parameter client: a MongoClient
- parameter databaseName: A String identifying the requested database

- returns: a reference to the requested database
func close()
Close connection to database
func drop() -> Result
Drops the current database, deleting the associated data files
func name() -> String
- returns: a string, the name of the current database
func createCollection(name collectionName: String, options: BSON?) -> Result
Create new Collection

- parameter name: String, name of collection to be created
- parameter options: BSON document listing options for new collection

- returns: MongoCollection
func getCollection(name collectionName: String) -> MongoCollection?
MongoCollection referenced by name

- parameter name: String collection name

- returns: MongoCollection
func collectionNames() -> [String]
- returns: String Array of current database collections' names
class GridFile
File class of GridFS
- Author:
Rockford Wei
func init(_ from: OpaquePointer?) throws
constructor of GridFile class object
- parameters:
- from: a mongoc_gridfs_file_t for handle the file, not nullable
- throws:
MongoClientError
func init(gridFS:OpaquePointer?, from: String ) throws
constructor of a GridFile class object
- parameters:
- gridFS: mongo_gridfs_t for gridfs handle, not nullable
- from: a mongoc_gridfs_file_t for handle the file, not nullable
- throws:
MongoClientError
func close()
destructor of a GridFile class object
defer it as the most preferable practice
var id: String
id (oid) property of GridFile, readonly.
var md5: String
md5 property of GridFile, readonly.
var aliases: BSON
aliases property of GridFile, readonly.
var contentType: String
content type property of GridFile, readonly.
var length: Int64
length (in bytes) property of GridFile, readonly.
var uploadDate: Int64
upload date property of GridFile, in unix epoch time format, readonly.
var fileName: String
name of the grid file object, readonly
var metaData: BSON
meta data of the grid file object, in bson format, readonly
func download(to: String) throws -> Int
download a file.
- parameters:
- to: the destinated file name on local drive
- throws:
MongoClientError if failed to write
- returns:
Bytes that written
enum Whence
Offset measurement reference for seek() method
func tell() -> UInt64
get the current file cursor position
- returns
UInt64 stands for the current file cursor positon
func seek(cursor: Int64, whence:Whence = .begin) throws
set the current file position
- parameters:
- cursor: new position
- whence: whence of new position, i.e., file begin, current or end of file.
- throws
MongoClientError if failed to seek
func partiallyRead(amount: UInt32, timeout:UInt32 = 0) throws -> [UInt8]
partially read some bytes from the remote file
- parameters:
- amount: bytes count to read
- timeout: milliseconds to wait. default 0 to return immediately
- returns:
an array of bytes as outcome
- throws:
MongoClientError if failed to read
func partiallyWrite(bytes:[UInt8], timeout:UInt32 = 0) throws -> Int
partially write some bytes to the remote file
- parameters:
- bytes: an array of bytes to write
- timeout: milliseconds to wait. default 0 to return immediately
- returns:
bytes totally written
- throws:
MongoClientError if failed to read
func delete() throws
remove the file from server
- throws:
MongoClientError
class GridFS
GridFS class for MongoDB
- Author:
Rockford Wei
func init(client: MongoClient, database: String, prefix: String? = nil) throws
constructor of gridfs
- parameters:
- client: MongoClient
- database: database name of gridfs
- prefix: prefix of the file system
- throws:
MongoClientError, if failed to get the expected handle
func close()
destuctor of gridfs, a defer is suggested to use this method.
func list(filter: BSON? = nil) throws -> [GridFile]
list all files on the gridfs
- parameters:
- filter: a bson to determine which kind of files and how to list, such as order by upload date, or by size. nil for all files.
- throws:
MongoClientError if failed
- returns:
[GridFile]: array to hold a list of GridFile objects
func upload(from: String, to: String, contentType:String = "text/plain", md5:String = "", metaData: BSON? = nil, aliases:BSON? = nil) throws -> GridFile
grid file uploader.
NOTE:for macOS, mongoc library MUST fix the mongoc-gridfs-file.h line 34-41 and add BSON_API to the file_set methods
- parameters:
- from: local file name to upload, string
- to: remote file name as expected, string
- contentType: content type of the file as a string, optional. Default is "text/plain"
- md5: MD5 hash of the file as a string, optional.
- metaData: meta data of the file in BSON format, optiona.
- aliases: aliases of the file in BSON format, optional.
func download(from: String, to: String) throws -> Int
download a file by its name on server
- parameters:
- from: file name on server
- to: local path to save the downloaded file
- throws:
MongoClientError if not file found or failed to download
- returns:
bytes that downloaded
func search(name: String) throws -> GridFile
search for a file on the gridfs
- parameters:
- name: name of file to find
- returns:
a grid file object if found
- throws:
MongoClientError if failed or not found
func delete(name: String) throws
delete a file from the server
- parameters:
- name: name of the file to delete
- throws:
MongoClientError if failed or not found
func drop() throws
Requests that an entire GridFS be dropped, including all files associated with
- throws:
MongoClientError if failed
extension MongoClient
func gridFS(database: String, prefix: String? = nil) throws -> GridFS
an express way of calling gridfs. Please note to defer a close() immediately.
parameters:
- database: database name of the gridfs
- prefix: name of starting with of the gridfs, nullable
returns:
- gridfs handle if success
throws:
- MongoClientError if failed to open such a handle