Creates a new MongoLite client instance.
dbPathOrOptions: Either a string path to the SQLite database file (e.g.,'./mydb.sqlite',':memory:') or an options object.MongoLiteOptions:filePath: string — Path to the SQLite database file.verbose?: boolean — (Optional) Enable verbose logging from thesqlite3driver.
Explicitly opens the database connection. Operations will automatically connect if the DB is not already open.
Closes the database connection.
Lists all collections (tables) in the database.
const collections = await client.listCollections().toArray();
console.log('Available collections:', collections);Gets a reference to a collection (table).
name: The name of the collection.- Returns a
MongoLiteCollectioninstance.
Replicates every insert, update and delete to an upstream MongoDB deployment.
Requires the optional mongodb peer dependency.
options.connectionString: Upstream connection string (required).options.collections/exclude/collectionMap: What to replicate, and under what names.options.onConflict: What to do when a push loses a race. Defaults to the server winning.options.versioning: Conditional writes against_v. Defaults totrue.- Returns a
SyncReplicator— callstart()on it.
const sync = client.syncToMongo({ connectionString: process.env.MONGO_URL! });
await sync.start();
// …
await sync.stop({ flush: true });See Syncing to MongoDB for the full option list, authentication, resilience behaviour and monitoring.
Replicates to a remote HTTP API, which applies the changes to MongoDB on this client's behalf. For deployments that cannot reach the database directly.
options.baseUrl/options.database: Where to post (required).options.getAuthHeaders: Resolved before every request, so short-lived tokens refresh.options.fetch: Supply your ownfetch(e.g.ofetch); defaults to the global one.
Mount createSyncReceiver from @semics-tech/mongolite/server on the API to receive
the messages. See Syncing to MongoDB.
The backend-agnostic form of the above. Pass any SyncSink implementation to
replicate to something other than a MongoDB deployment — an HTTP API, a queue,
or a test double.
Represents a collection and provides methods to interact with its documents. T is a generic type for your document structure, which must extend DocumentWithId (i.e., have an optional _id: string field).
Inserts a single document. If _id is not provided, a UUID will be generated.
- Returns
{ acknowledged: boolean; insertedId: string }.
Inserts multiple documents in a single operation.
- Returns
{ acknowledged: boolean; insertedIds: string[] }.
Finds a single document matching the filter. Returns null if not found.
Finds multiple documents matching the filter. Returns a chainable FindCursor.
Updates a single document matching the filter.
- Returns
{ acknowledged: boolean; matchedCount: number; modifiedCount: number; upsertedId: string | null }.
Updates all documents matching the filter.
Deletes a single document matching the filter.
- Returns
{ acknowledged: boolean; deletedCount: number }.
Deletes all documents matching the filter.
Replaces a single document matching the filter with the provided document.
Finds a document, updates it, and returns the original or updated document.
Finds a document, deletes it, and returns the deleted document.
Finds a document, replaces it, and returns the original or new document.
Returns an array of distinct values for the given field.
Returns the count of documents matching the filter.
Returns a fast estimate of the total document count.
Drops the collection (deletes the underlying table).
Runs an aggregation pipeline; call .toArray() to get the results. Supported stages: $match (including $expr), $project (including computed fields), $addFields/$set, $sort, $limit, $skip, $count, $group, $unwind (including preserveNullAndEmptyArrays and includeArrayIndex), $replaceRoot/$replaceWith, and $lookup (equality form from/localField/foreignField/as against another collection in the same database; the pipeline/let form is not supported). $group supports the accumulators $sum, $avg, $min, $max, $push, $addToSet, $first, $last and $count. Expressions support field paths and a common subset of operators ($add, $subtract, $multiply, $divide, $mod, $concat, $toUpper, $toLower, comparison and boolean operators, $cond, $ifNull, $size, $arrayElemAt, $first, $last, $literal). Unknown stages, accumulators or expression operators throw an error rather than being ignored. See COMPATIBILITY.md for the full table.
There is no multi-document transaction API (no sessions, startTransaction or withTransaction). Each write is atomic on its own, and insertMany runs as a single SQLite transaction.
Opens a change stream to watch for changes on this collection.
See CHANGE_STREAMS.md for full documentation.
Returned by collection.find(). Supports chaining before execution.
Fetches all matching documents into an array.
Returns the next document, or null when exhausted.
Limits the number of documents returned.
Skips the first N documents.
Sorts results. Example: { age: -1, name: 1 } (1 = ascending, -1 = descending).
Specifies which fields to include or exclude in results.
Returns the number of documents matching the cursor's filter (like MongoDB's cursor.count(), it ignores skip/limit but never the filter).
Creates an index on the specified field(s).
fieldOrSpec: A field name string or an index spec object, e.g.{ name: 1, age: -1 }.options:unique: Enforce uniqueness.name: Custom index name.sparse: Ignore documents without the indexed field.
- Returns
{ acknowledged: boolean; name: string }.
// Simple index
await collection.createIndex({ name: 1 });
// Unique index
await collection.createIndex({ email: 1 }, { unique: true });
// Compound index
await collection.createIndex({ name: 1, age: -1 });
// Nested field index
await collection.createIndex({ 'address.city': 1 });Lists all indexes on the collection. Each IndexInfo contains name, key, and unique.
Drops the named index. Returns { acknowledged: boolean; name: string }.
Drops all indexes except the one on _id.
| Operator | Description |
|---|---|
{ field: value } or { field: { $eq: value } } |
Equals |
{ field: { $ne: value } } |
Not equals |
{ field: { $gt: value } } |
Greater than |
{ field: { $gte: value } } |
Greater than or equal |
{ field: { $lt: value } } |
Less than |
{ field: { $lte: value } } |
Less than or equal |
{ field: { $in: [v1, v2] } } |
In array |
{ field: { $nin: [v1, v2] } } |
Not in array |
{ field: { $regex: pattern } } |
Matches regular expression |
{ field: { $size: n } } |
Array has N elements |
{ field: { $type: typeName } } |
Field is of given type |
{ field: { $mod: [divisor, remainder] } } |
Modulo |
| Operator | Description |
|---|---|
{ $and: [f1, f2] } |
Logical AND |
{ $or: [f1, f2] } |
Logical OR |
{ $nor: [f1, f2] } |
Logical NOR |
{ field: { $not: expr } } |
Negates a single operator expression |
| Operator | Description |
|---|---|
{ field: { $exists: boolean } } |
Field exists (or not) |
| Operator | Description |
|---|---|
{ field: { $all: [v1, v2] } } |
Array contains all values |
{ field: { $elemMatch: query } } |
At least one element matches the query |
| Operator | Description |
|---|---|
$set |
Sets field values |
$unset |
Removes fields |
$inc |
Increments numeric fields |
$mul |
Multiplies numeric fields |
$min |
Sets field to minimum of current and given value |
$max |
Sets field to maximum of current and given value |
$push |
Appends a value to an array (supports $each) |
$pull |
Removes matching values from an array |
$addToSet |
Adds a value to an array only if it doesn't already exist |
$pop |
Removes the first (-1) or last (1) element of an array |
$currentDate |
Sets a field to the current date |
// $set and $inc
await collection.updateOne({ _id: id }, { $set: { name: 'Bob' }, $inc: { age: 1 } });
// $push with $each
await collection.updateOne({ _id: id }, { $push: { scores: { $each: [90, 92, 85] } } });
// $pull
await collection.updateOne({ _id: id }, { $pull: { scores: 0 } });
// $addToSet
await collection.updateOne({ _id: id }, { $addToSet: { tags: 'new-tag' } });