API: client
Source:
mongodb/client.ts
Define a common type for input to functions that accept either a plain JavaScript object (which will be implicitly converted to DBObject) or an existing DBObject wrapper instance.
Usage
import { client } from "sdk/mongodb";
import { response } from "sdk/http";
let mongoClient = client.getClient();
let collection = mongoClient.getDB("db").getCollection("people");
let person = client.createBasicDBObject()
.append("_id", "jo")
.append("name", "Jo Bloggs");
// or directly create an Object:
// const person = {"_id": "jo", "name": "Jo Bloggs"};
collection.insert(person);
let query = client.createBasicDBObject().append("_id", "jo");
let cursor = collection.find(query)
let result = cursor.one();
response.println("Result: " + result._id);
response.flush();
response.close();Classes
DBObject
DBObject object represents a BSON document used for queries, insertions, and updates.
It wraps the underlying native Java object.
Methods
append
append (key:string, value:any):DBObjectAppends a key-value pair to the DBObject.
@param key The field name.
@param value The value to append.
@returns The current DBObject instance for chaining.
toJson
toJson ():any}Converts the DBObject to a standard JavaScript object representation (JSON).
@returns A plain JavaScript object.
markAsPartialObject
markAsPartialObject ():voidMarks the object as a partial object (used internally by MongoDB driver).
isPartialObject
isPartialObject ():booleanChecks if the object is a partial object.
@returns True if partial, false otherwise.
containsField
containsField (key:string):booleanChecks if the DBObject contains a field with the specified key.
@param key The field name.
@returns True if the field exists, false otherwise.
get
get (key:string):anyGets the value associated with the given key.
@param key The field name.
@returns The field value.
put
put (key:string, value:any):anyPuts a key-value pair into the DBObject.
@param key The field name.
@param value The value to put.
@returns The previous value associated with the key, or null.
removeField
removeField (key:string):anyRemoves a field from the DBObject.
@param key The field name to remove.
@returns The removed field value.
Client
Client object wrapper for connecting to MongoDB.
Methods
getDB
getDB (name?:string):DBRetrieves a database instance.
@param name Optional name of the database. If not provided, the default database name is used.
@returns A DB instance.
DB
DB object wrapper for a MongoDB database.
Methods
getCollection
getCollection (name:string):DBCollectionRetrieves a collection instance from the database.
@param name The name of the collection.
@returns A DBCollection instance.
DBCollection
DBCollection object wrapper for a MongoDB collection.
Methods
insert
insert (dbObject:DBInput):voidInserts a document into the collection.
@param dbObject The document to insert (can be a plain JS object or DBObject).
find
find (query?:DBInput, projection?:DBInput):DBCursorFinds documents matching the query.
@param query The query specification (can be a plain JS object or DBObject).
@param projection The fields to include or exclude (can be a plain JS object or DBObject).
@returns A DBCursor for iterating over results.
findOne
findOne (query:DBInput, projection:DBInput, sort:DBInput):DBObjectFinds a single document matching the query.
@param query The query specification.
@param projection The fields to include or exclude.
@param sort The sorting specification.
@returns The found document as a DBObject.
findOneById
findOneById (id:string, projection?:DBInput):DBObjectFinds a single document by its string ID.
@param id The string ID of the document.
@param projection The fields to include or exclude.
@returns The found document as a DBObject.
count
count (query?:DBInput):numberCounts the number of documents in the collection, optionally filtered by a query.
@param query Optional query to filter the count.
@returns The number of documents.
getCount
getCount (query:DBInput):numberGets the count of documents (alias for count).
@param query Optional query to filter the count.
@returns The number of documents.
createIndex
createIndex (keys:DBInput, options:DBInput):voidCreates an index on the collection.
@param keys The index key specification.
@param options Optional index options.
createIndexForField
createIndexForField (name:string):voidCreates an index on a single field by name.
@param name The name of the field to index.
distinct
distinct (name:string, query:DBInput, keys:DBInput):voidRetrieves 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 usingkeys.nativeifkeysis provided.
@param name The field name.
@param query Optional query to filter results.
@param keys Optional keys to use for distinct (replaces 'name' if provided and query exists).
dropIndex
dropIndex (index:string|DBInput):voidDrops a specified index.
@param index The name of the index or the DBObject representing the index keys.
dropIndexByName
dropIndexByName (name:string):voidDrops a specified index by name.
@param name The name of the index.
dropIndexes
dropIndexes ():voidDrops all indexes on the collection.
remove
remove (query:DBInput):voidRemoves documents from the collection matching the query.
@param query The deletion query specification.
rename
rename (newName:string):voidRenames the collection.
@param newName The new name for the collection.
save
save (dbObject:DBInput):voidSaves a document to the collection. If the document has an
_id, it performs an update;
otherwise, it performs an insert.
@param dbObject The document to save.
update
update (query:DBInput, update:DBInput, upsert?:boolean, multi?:boolean):voidUpdates documents in the collection matching the query.
@param query The update query specification.
@param update The update operation specification (e.g., {$set: {...}}).
@param upsert If true, creates a new document if no documents match the query.
@param multi If true, updates all documents matching the query; otherwise, only one.
updateMulti
updateMulti (query:DBInput, update:DBInput):voidUpdates multiple documents in the collection matching the query.
(Equivalent to callingupdatewithmulti=trueandupsert=trueimplicitly).
@param query The update query specification.
@param update The update operation specification.
getNextId
getNextId ():numberCalculates the next sequential ID based on the largest existing
_idin the collection.
Assumes_idis a numeric field.
@returns The next available sequential ID (starting at 1 if collection is empty).
generateUUID
generateUUID ():stringGenerates a new random UUID (Universally Unique Identifier).
@returns A string representing the UUID.
DBCursor
DBCursor object wrapper for iterating over results of a MongoDB query.
Methods
one
one ():DBObjectReturns the single result from the cursor.
@returns A DBObject representing the document.
batchSize
batchSize (numberOfElements:number):DBCursorSets the batch size for the cursor.
@param numberOfElements The batch size.
@returns The DBCursor instance for chaining.
getBatchSize
getBatchSize ():numberGets the current batch size.
@returns The batch size.
getCollection
getCollection ():DBCollectionGets the collection associated with this cursor.
@returns The DBCollection instance.
getCursorId
getCursorId ():stringGets the cursor ID.
@returns The cursor ID string.
getKeysWanted
getKeysWanted ():DBObjectGets the projection object (fields wanted) used in the query.
@returns The projection DBObject.
getLimit
getLimit ():numberGets the limit set on the cursor.
@returns The limit number.
close
close ():voidCloses the cursor.
hasNext
hasNext ():booleanChecks if there is a next document in the cursor.
@returns True if there is a next document, false otherwise.
next
next ():DBObjectRetrieves the next document in the cursor.
@returns The next document as a DBObject.
getQuery
getQuery ():DBObjectGets the query object used to create this cursor.
@returns The query DBObject.
length
length ():numberGets the number of documents matched by the query.
@returns The total number of documents.
sort
sort (orderBy:DBInput):DBCursorSpecifies the order in which the query returns the results.
@param orderBy The sorting specification (e.g., {field: 1} for ascending).
@returns The DBCursor instance for chaining.
limit
limit (limit:number):DBCursorLimits the number of results to be returned.
@param limit The maximum number of documents to return.
@returns The DBCursor instance for chaining.
min
min (min:number):DBCursorSpecifies the exclusive upper bound for a specific index.
@param min The minimum value.
@returns The DBCursor instance for chaining.
max
max (max:number):DBCursorSpecifies the exclusive upper bound for a specific index.
@param max The maximum value.
@returns The DBCursor instance for chaining.
maxTime
maxTime (maxTime:number):DBCursorSets a timeout for the server to execute the query.
@param maxTime The maximum time in milliseconds.
@returns The DBCursor instance for chaining.
size
size ():numberGets the size of the result set.
@returns The size number.
skip
skip (numberOfElements:number):DBCursorSkips the specified number of documents.
@param numberOfElements The number of documents to skip.
@returns The DBCursor instance for chaining.