Client
Overview
Module
- package:
@aerokit/sdk/mongodb - source: mongodb/client.ts
- last updated:
The Client module provides a high-level API for connecting to MongoDB databases and performing operations on collections. It abstracts the underlying MongoDB Java driver, allowing developers to interact with MongoDB using familiar JavaScript objects and methods. The module includes classes for managing database connections, accessing collections, and executing queries, making it easier to integrate MongoDB into applications built on the Dirigible platform.
Key Features:
- MongoDB Connection Management: The
Clientclass allows for connecting to MongoDB using a connection URI and credentials. - Database and Collection Access: The
DBandDBCollectionclasses provide methods for accessing databases and collections, as well as performing CRUD operations. - Querying and Cursor Management: The
DBCursorclass enables iterating over query results with support for sorting, limiting, and batch processing.
Use Cases:
- Data Storage and Retrieval: Developers can use this module to store and retrieve data in MongoDB, leveraging its flexible document model.
- Integration with MongoDB: By providing a JavaScript-friendly API, this module facilitates integration with MongoDB in applications running on the Dirigible platform.
Example Usage:
import { Client } from "@aerokit/sdk/mongodb";
// Create a MongoDB client and connect to the database
const client = new Client("mongodb://localhost:27017", "username", "password");
const db = client.getDB("myDatabase");
const collection = db.getCollection("myCollection");
// Insert a document into the collection
collection.insert({ name: "Alice", age: 30 });
// Find documents in the collection
const cursor = collection.find({ age: { $gt: 25 } });
while (cursor.hasNext()) {
const doc = cursor.next();
console.log(doc);
}Classes
DBObject
append()
Appends a key-value pair to the DBObject.
tsappend(key: string, value: any): DBObject;
Parameter Type Description keystringThe field name. valueanyThe value to append. Returns
- Type:
DBObject- Description: The current DBObject instance for chaining.
toJson()
Converts the DBObject to a standard JavaScript object representation (JSON).
tstoJson(): void;Returns
- Type:
void- Description: A plain JavaScript object.
markAsPartialObject()
Marks the object as a partial object (used internally by MongoDB driver).
tsmarkAsPartialObject(): void;Returns
- Type:
void- Description:
isPartialObject()
Checks if the object is a partial object.
tsisPartialObject(): boolean;Returns
- Type:
boolean- Description: True if partial, false otherwise.
containsField()
Checks if the DBObject contains a field with the specified key.
tscontainsField(key: string): boolean;
Parameter Type Description keystringThe field name. Returns
- Type:
boolean- Description: True if the field exists, false otherwise.
get()
Gets the value associated with the given key.
tsget(key: string): any;
Parameter Type Description keystringThe field name. Returns
- Type:
any- Description: The field value.
put()
Puts a key-value pair into the DBObject.
tsput(key: string, value: any): any;
Parameter Type Description keystringThe field name. valueanyThe value to put. Returns
- Type:
any- Description: The previous value associated with the key, or null.
removeField()
Removes a field from the DBObject.
tsremoveField(key: string): any;
Parameter Type Description keystringThe field name to remove. Returns
- Type:
any- Description: The removed field value.
Client
getDB()
Retrieves a database instance.
tsgetDB(name: string): DB;
Parameter Type Description namestringOptional name of the database. If not provided, the default database name is used. Returns
- Type:
DB- Description: A DB instance.
DB
getCollection()
Retrieves a collection instance from the database.
tsgetCollection(name: string): DBCollection;
Parameter Type Description namestringThe name of the collection. Returns
- Type:
DBCollection- Description: A DBCollection instance.
DBCollection
insert()
Inserts a document into the collection.
tsinsert(dbObject: DBInput): void;
Parameter Type Description dbObjectDBInputThe document to insert (can be a plain JS object or DBObject). Returns
- Type:
void- Description:
find()
Finds documents matching the query.
tsfind(query: DBInput, projection: DBInput): DBCursor;
Parameter Type Description queryDBInputThe query specification (can be a plain JS object or DBObject). projectionDBInputThe fields to include or exclude (can be a plain JS object or DBObject). Returns
- Type:
DBCursor- Description: A DBCursor for iterating over results.
findOne()
Finds a single document matching the query.
tsfindOne(query: DBInput, projection: DBInput, sort: DBInput): DBObject;
Parameter Type Description queryDBInputThe query specification. projectionDBInputThe fields to include or exclude. sortDBInputThe sorting specification. Returns
- Type:
DBObject- Description: The found document as a DBObject.
findOneById()
Finds a single document by its string ID.
tsfindOneById(id: string, projection: DBInput): DBObject;
Parameter Type Description idstringThe string ID of the document. projectionDBInputThe fields to include or exclude. Returns
- Type:
DBObject- Description: The found document as a DBObject.
count()
Counts the number of documents in the collection, optionally filtered by a query.
tscount(query: DBInput): number;
Parameter Type Description queryDBInputOptional query to filter the count. Returns
- Type:
number- Description: The number of documents.
getCount()
Gets the count of documents (alias for count).
tsgetCount(query: DBInput): number;
Parameter Type Description queryDBInputOptional query to filter the count. Returns
- Type:
number- Description: The number of documents.
createIndex()
Creates an index on the collection.
tscreateIndex(keys: DBInput, options: DBInput): void;
Parameter Type Description keysDBInputThe index key specification. optionsDBInputOptional index options. Returns
- Type:
void- Description:
createIndexForField()
Creates an index on a single field by name.
tscreateIndexForField(name: string): void;
Parameter Type Description namestringThe name of the field to index. Returns
- Type:
void- Description:
distinct()
Retrieves the distinct values for a specified field across a collection. NOTE: The signature in the original code seems slightly off compared to typical MongoDB drivers. This implementation follows the original structure using keys.native if keys is provided.
tsdistinct(name: string, query: DBInput, keys: DBInput): void;
Parameter Type Description namestringThe field name. queryDBInputOptional query to filter results. keysDBInputOptional keys to use for distinct (replaces 'name' if provided and query exists). Returns
- Type:
void- Description:
dropIndex()
Drops a specified index.
tsdropIndex(index: any): void;
Parameter Type Description indexanyThe name of the index or the DBObject representing the index keys. Returns
- Type:
void- Description:
dropIndexByName()
Drops a specified index by name.
tsdropIndexByName(name: string): void;
Parameter Type Description namestringThe name of the index. Returns
- Type:
void- Description:
dropIndexes()
Drops all indexes on the collection.
tsdropIndexes(): void;Returns
- Type:
void- Description:
remove()
Removes documents from the collection matching the query.
tsremove(query: DBInput): void;
Parameter Type Description queryDBInputThe deletion query specification. Returns
- Type:
void- Description:
rename()
Renames the collection.
tsrename(newName: string): void;
Parameter Type Description newNamestringThe new name for the collection. Returns
- Type:
void- Description:
save()
Saves a document to the collection. If the document has an _id, it performs an update; otherwise, it performs an insert.
tssave(dbObject: DBInput): void;
Parameter Type Description dbObjectDBInputThe document to save. Returns
- Type:
void- Description:
update()
Updates documents in the collection matching the query.
tsupdate(query: DBInput, update: DBInput, upsert: boolean, multi: boolean): void;
Parameter Type Description queryDBInputThe update query specification. updateDBInputThe update operation specification (e.g., {$set: {...}}). upsertbooleanIf true, creates a new document if no documents match the query. multibooleanIf true, updates all documents matching the query; otherwise, only one. Returns
- Type:
void- Description:
updateMulti()
Updates multiple documents in the collection matching the query. (Equivalent to calling update with multi=true and upsert=true implicitly).
tsupdateMulti(query: DBInput, update: DBInput): void;
Parameter Type Description queryDBInputThe update query specification. updateDBInputThe update operation specification. Returns
- Type:
void- Description:
getNextId()
Calculates the next sequential ID based on the largest existing _id in the collection. Assumes _id is a numeric field.
tsgetNextId(): number;Returns
- Type:
number- Description: The next available sequential ID (starting at 1 if collection is empty).
generateUUID()
Generates a new random UUID (Universally Unique Identifier).
tsgenerateUUID(): string;Returns
- Type:
string- Description: A string representing the UUID.
DBCursor
one()
Returns the single result from the cursor.
tsone(): DBObject;Returns
- Type:
DBObject- Description: A DBObject representing the document.
batchSize()
Sets the batch size for the cursor.
tsbatchSize(numberOfElements: number): DBCursor;
Parameter Type Description numberOfElementsnumberThe batch size. Returns
- Type:
DBCursor- Description: The DBCursor instance for chaining.
getBatchSize()
Gets the current batch size.
tsgetBatchSize(): number;Returns
- Type:
number- Description: The batch size.
getCollection()
Gets the collection associated with this cursor.
tsgetCollection(): DBCollection;Returns
- Type:
DBCollection- Description: The DBCollection instance.
getCursorId()
Gets the cursor ID.
tsgetCursorId(): string;Returns
- Type:
string- Description: The cursor ID string.
getKeysWanted()
Gets the projection object (fields wanted) used in the query.
tsgetKeysWanted(): DBObject;Returns
- Type:
DBObject- Description: The projection DBObject.
getLimit()
Gets the limit set on the cursor.
tsgetLimit(): number;Returns
- Type:
number- Description: The limit number.
close()
Closes the cursor.
tsclose(): void;Returns
- Type:
void- Description:
hasNext()
Checks if there is a next document in the cursor.
tshasNext(): boolean;Returns
- Type:
boolean- Description: True if there is a next document, false otherwise.
next()
Retrieves the next document in the cursor.
tsnext(): DBObject;Returns
- Type:
DBObject- Description: The next document as a DBObject.
getQuery()
Gets the query object used to create this cursor.
tsgetQuery(): DBObject;Returns
- Type:
DBObject- Description: The query DBObject.
length()
Gets the number of documents matched by the query.
tslength(): number;Returns
- Type:
number- Description: The total number of documents.
sort()
Specifies the order in which the query returns the results.
tssort(orderBy: DBInput): DBCursor;
Parameter Type Description orderByDBInputThe sorting specification (e.g., {field: 1} for ascending). Returns
- Type:
DBCursor- Description: The DBCursor instance for chaining.
limit()
Limits the number of results to be returned.
tslimit(limit: number): DBCursor;
Parameter Type Description limitnumberThe maximum number of documents to return. Returns
- Type:
DBCursor- Description: The DBCursor instance for chaining.
min()
Specifies the exclusive upper bound for a specific index.
tsmin(min: number): DBCursor;
Parameter Type Description minnumberThe minimum value. Returns
- Type:
DBCursor- Description: The DBCursor instance for chaining.
max()
Specifies the exclusive upper bound for a specific index.
tsmax(max: number): DBCursor;
Parameter Type Description maxnumberThe maximum value. Returns
- Type:
DBCursor- Description: The DBCursor instance for chaining.
maxTime()
Sets a timeout for the server to execute the query.
tsmaxTime(maxTime: number): DBCursor;
Parameter Type Description maxTimenumberThe maximum time in milliseconds. Returns
- Type:
DBCursor- Description: The DBCursor instance for chaining.
size()
Gets the size of the result set.
tssize(): number;Returns
- Type:
number- Description: The size number.
skip()
Skips the specified number of documents.
tsskip(numberOfElements: number): DBCursor;
Parameter Type Description numberOfElementsnumberThe number of documents to skip. Returns
- Type:
DBCursor- Description: The DBCursor instance for chaining.
