For AI agents: the complete documentation index is available at https://silt-db.dev/llms.txt, the full documentation bundle is available at https://silt-db.dev/llms-full.txt, and this page is available as Markdown at https://silt-db.dev/reference/mongodb.md.

Driver API and options

This page lists Silt-specific initialization, accepted options, and driver behavior. For ordinary API usage, use the official MongoDB Node driver documentation. Start with Silt initialization, and check the central MongoDB compatibility limits before reusing application code.

Initialization and ownership

import { MongoClient } from '@silt-db/mongodb';

const fromFile = new MongoClient('app.sqlite', { dbName: 'app' });
const fromOptions = new MongoClient({ filename: 'other.sqlite', dbName: 'app' });
InputBehavior
SQLite filename plus optionsOpens through @silt-db/sqlite, respecting platform export conditions; the client owns the opened engine.
{ filename, ...options }Object form of filename opening. The default filename is silt.sqlite.
{ driver, ...options }Uses an application-supplied SQLite driver; it remains open unless closeDriver: true.
{ database, dbName?, closeDatabase? }Reuses an already open asynchronous Silt engine. The engine remains open unless closeDatabase: true. Configure it when opening it; additional SQLite opening options are rejected here.

The client's database name defaults to test; dbName sets its name. connect() returns the client and runs automatically before the first database operation. MongoClient.connect(filenameOrOptions, options?) is also available. MongoDB network URIs such as mongodb://... are rejected.

For worker-backed Node concurrency, first open a file with @silt-db/sqlite/server and supply that engine as { database }. Filename opening through this facade does not automatically select the server worker driver. See connections and options for SQLite configuration and ownership.

close() closes the client's cursors, ends its sessions, and closes its owned engine. Repeated calls share the same shutdown operation. Pending session operations settle before that session is ended. An explicitly closed client cannot be reconnected. Client, session, and cursor objects support asynchronous disposal.

One database per SQLite file

client.db() and client.db(configuredName) return the same cached Db. Passing any other database name throws MongoCompatibilityError. new Db(client, name) enforces the same rule. Separate databases require separate SQLite files.

dbName is a client API label, not a storage namespace or security boundary. Opening the same SQLite file with another configured label accesses the same database. Db.databaseName, Collection.dbName, and Collection.namespace report the configured name; the latter remains the familiar database.collection string.

Mongo and core Silt APIs share document collections and indexes. A collection named notes maps to the same table through either API. $lookup, $unionWith, and nested pipelines use those collection names directly. ShareDB snapshot/operation tables and custom SQL/BLOB tables are separate. Use the ShareDB adapter for ShareDB operations and subscriptions.

Database methodAccepted options
collection(name)None
createCollection(name)session
listCollections(filter)session, nameOnly
collections()session
dropCollection(name), dropDatabase()session

listCollections() returns a stateful cursor; filtering its metadata runs in SQL. collections() returns collection handles. Reads of absent collections return empty results without creating a persistent collection. Collection creation options for capped collections, validation, time series, and views are unsupported.

dropDatabase() drops all ordinary Silt document collections and their indexes, including collections created through the core API. It preserves the SQLite file, ShareDB snapshot/operation tables, and custom SQL/BLOB tables. dropCollection(name) affects the same shared collection through both APIs.

Collection operations and options

Options below are the accepted facade options. Unknown options are rejected, including MongoDB options that would otherwise be silently ignored.

MethodAccepted options
find(filter), findOne(filter)session, sort, projection, skip, limit, batchSize
aggregate(pipeline)session, batchSize, let
countDocuments(filter)session, skip, limit
estimatedDocumentCount()None
distinct(field, filter)session
insertOne(document)session
insertMany(documents)session, ordered
updateOne(filter, update), updateMany(filter, update)session, upsert, arrayFilters
replaceOne(filter, replacement)session, upsert
deleteOne(filter), deleteMany(filter)session
bulkWrite(operations)session, ordered
drop()session

sort accepts an object of field/direction pairs, an array of pairs, or a field string for ascending order. Directions are 1, -1, asc, desc, ascending, or descending. Find limits use the magnitude of a negative limit; zero means no limit. Skip and batch-size arguments must be nonnegative safe integers. Aggregate cursor limits must be positive.

projection: {} leaves find and compound results unchanged. Aggregation $project follows the core aggregation compiler's validation rules. let supplies aggregation variables; the facade does not add MongoDB command-level let support to writes or find operations.

Writes return acknowledged result objects. Inserts expose insertedId or insertedCount plus indexed insertedIds. Updates expose matchedCount, modifiedCount, upsertedCount, and upsertedId. Deletes expose deletedCount. The core's documented update semantics and numeric limits still apply, including the narrow final-JSON modifiedCount difference for a pipeline that removes and implicitly restores _id.

Stateful cursors

find, aggregate, listCollections, and listIndexes return cursors that maintain one consumption position.

MethodBehavior
next()Consumes the next document or returns null on exhaustion.
tryNext()Same local behavior as next(); there is no server network batch to poll.
hasNext()Peeks without consuming the next document.
toArray()Collects only the remaining documents.
forEach(callback)Consumes remaining documents; returning false stops and closes the cursor.
Async iterationConsumes remaining documents; normal completion and early exit clean up resources.
close()Releases the cursor and its buffered row or underlying iterator.
rewind()Resets the cursor synchronously for reconfiguration and schedules prior iterator cleanup. Returns void; the next consumption reruns the query.
batchSize(n)Validates a nonnegative integer transport hint; engine configuration determines actual SQLite buffering.

Configure find cursors with sort, skip, limit, or project before consumption or after rewinding. clone() creates an independent unconsumed find cursor. Aggregate cursors support match, project, sort, skip, limit, group, and unwind stage helpers before consumption. Both provide explain(), which returns SQL, bindings, and SQLite's query plan. Its format differs from a MongoDB explain document.

A server cursor can hold a WAL reader lease and snapshot. The configured reader pool and cursor idle timeout bound these resources. Portable writer cursors use SQLite-backed result spooling; actual temporary storage depends on the platform. cursorBatchSize controls portable page copying and readBatchSize controls server worker transfers. Facade batchSize() does not override those engine settings. toArray() always allocates its returned array.

JavaScript cursor transforms such as .map() are outside this API. Node .stream() and cursor flags are explicitly unsupported. Use SQL projections, aggregation stages, or ordinary application processing after receiving documents.

Atomic find-and-modify operations

findOneAndUpdate, findOneAndReplace, and findOneAndDelete select and mutate a document in one SQLite transaction. Concurrent writers cannot intervene between those steps.

MethodAccepted options
findOneAndUpdate(filter, update)session, sort, projection, includeResultMetadata, upsert, arrayFilters, returnDocument
findOneAndReplace(filter, replacement)session, sort, projection, includeResultMetadata, upsert, returnDocument
findOneAndDelete(filter)session, sort, projection, includeResultMetadata

The default result is a document or null. Update and replace return the previous document unless returnDocument: 'after'; a default-before upsert returns null. includeResultMetadata: true returns { value, ok: 1, lastErrorObject }.

n is zero when nothing matched and no upsert occurred. Updates and replacements include updatedExisting; upserts also include upserted. Delete metadata includes n. The facade does not manufacture server operation times or cluster metadata. Projection is validated even when no document matches.

Batch writes and partial results

Facade insertMany and bulkWrite preserve successful writes before a later failure. ordered defaults to true, stopping at the first error. With ordered: false, subsequent operations are attempted. Within an explicit transaction, any failing batch stops and rolls back the transaction even when unordered.

bulkWrite accepts insertOne, updateOne, updateMany, replaceOne, deleteOne, and deleteMany entries. Entry bodies use their corresponding method's arguments, such as { updateOne: { filter, update, upsert, arrayFilters } }. A session belongs in the outer options.

BulkWriteResult exposes insertedCount, matchedCount, modifiedCount, deletedCount, upsertedCount, indexed insertedIds and upsertedIds, plus ok and isOk(). It also provides hasWriteErrors, getWriteErrorCount, getWriteErrorAt, getWriteErrors, getWriteConcernError, getUpsertedIdAt, and getRawResponse accessors.

MongoBulkWriteError exposes the partial result, indexed writeErrors, and count/ID getters. A WriteError contains index, code, errmsg, and op, with getOperation() and toJSON() accessors. Successful IDs refer to input operation positions. Unordered execution and partial-result bookkeeping are not a guarantee of identical scheduling or every bookkeeping detail of the official driver.

Facade updateMany selects candidate IDs in SQL and applies each update separately, rechecking the original predicate. A later document-dependent failure retains earlier successful documents outside a transaction. Currently the candidate-ID array uses O(matches) JavaScript memory; document filtering and update transformations still run in SQL. This differs from the core Silt API, whose insertMany and updateMany are atomic across each operation. Concurrent mutations can change whether a candidate still matches; precise MongoDB concurrent scheduling is not reproduced.

Index catalog

MethodAccepted options
createIndex(spec)session, name, unique
createIndexes(specifications)Outer session; each specification has key, optional name, and supported unique setting.
listIndexes()session, batchSize
indexes(), indexExists(nameOrNames)session
indexInformation()session, full
dropIndex(name), dropIndexes()session

Supported secondary indexes are Silt's nonunique compound and multikey indexes. unique: true is unsupported for secondary indexes. _id has an implicit uniqueness constraint; requesting the normal { _id: 1 } index returns _id_. That index cannot be dropped. dropIndex('*') and dropIndexes() remove secondary indexes.

listIndexes() returns a cursor; indexes() returns an array. indexInformation() returns a name-to-key-pairs mapping or full index descriptions with full: true. The catalog is persistent. A missing collection's listIndexes() reports namespace-not-found. Unique secondary, text, geo, TTL, sparse, partial, and other server-specific index options are rejected.

Sessions and transactions

startSession() and withSession(callback) create client-owned sessions. Session creation options are unsupported. A session supports startTransaction, commitTransaction, abortTransaction, withTransaction, inTransaction, and endSession.

Every operation in a transaction must receive that session. Its first operation acquires the SQLite transaction lease. Subsequent operations use the callback-scoped engine, including reads, so they see their own writes. Reads inside a transaction stay on its writer connection instead of escaping to a separate WAL reader.

An operation without the session may wait behind the active transaction; awaiting it from inside that transaction can deadlock. Concurrent operations on one session are unsupported. Cross-client or ended sessions are rejected. Consume transaction cursors before completing that transaction; a cursor cannot resume in a later transaction.

withTransaction(callback) commits after a successful callback and rolls back after a callback failure. A failed operation after entering the transaction aborts it; validation rejected before an operation begins need not acquire or abort a transaction. Manual start/commit/abort is also supported. End-session aborts an active transaction after an in-flight operation settles. Successful writes outside a transaction remain committed independently.

There is no automatic callback retry, transient-error labeling, retryable write protocol, distributed commit, causal clock, read/write concern, read-preference routing, or MongoDB transaction-option emulation. Configure local durability through SQLite initialization options.

Error differences

Duplicate _id errors map to numeric code 11000. Some directly recognized immutable-ID failures map to 66; other compiler or SQLite errors retain their original error class/message outside bulk handling. Bulk handling uses numeric generic code 2 for unmapped errors. A numeric code does not certify MongoDB's exact error taxonomy: for example, an invalid numeric update may surface as SQLite malformed JSON rather than the server's detailed type error.

Unsupported facade options raise MongoCompatibilityError; invalid facade arguments may raise MongoInvalidArgumentError. Compiler validation and unsupported-operator errors can propagate. Error messages, all server codes, and server resource limits are not exhaustively emulated.

For unsupported server features, BSON types, and shared query limitations, see MongoDB compatibility. An extensible inserted input document receives its generated _id.

See testing and compatibility evidence for driver contract, transaction, and platform validation scope.