NeoSQLite - NoSQL for SQLite with PyMongo-like API
NeoSQLite (new + nosqlite) is a pure Python library that provides a schemaless, PyMongo-like wrapper for interacting with SQLite databases. The API is designed to be familiar to those who have worked with PyMongo, providing a simple and intuitive way to work with document-based data in a relational database.
Keywords: NoSQL, NoSQLite, SQLite NoSQL, PyMongo alternative, SQLite document database, Python NoSQL, schemaless SQLite, MongoDB-like SQLite
Features
PyMongo-like API: A familiar interface for developers experienced with MongoDB.- NX-27017: MongoDB Wire Protocol Server — Use PyMongo with SQLite backend
- Schemaless Documents: Store flexible JSON-like documents.
- Lazy Cursor:
find()returns a memory-efficient cursor for iterating over results. - Raw Batch Support:
find_raw_batches()returns raw JSON data in batches for efficient processing. - Advanced Indexing: Single-key, compound-key, nested-key indexes, and FTS5 text search.
- TTL Indexes:
expireAfterSecondsexpiry with lazy auto-purge and an opt-in background sweeper. - ACID Transactions: Full
ClientSessionAPI with PyMongo 4.x parity using SQLite SAVEPOINTs. - Change Streams: Native SQLite triggers for
watch()— no replica set required. - Advanced Aggregation:
$setWindowFields,$graphLookup,$fill, streaming$facet,$indexStats, and more. - Tier-1 SQL Optimization: Dozens of operators translated to native SQL for 10-100x speedup, including BSON-aware
_idrange queries. - JavaScript Operators:
$functionand$whererun in an isolated out-of-process sandbox with selectable engines — preferringjsbox(QuickJS) over a patched Node.js runtime (see JavaScript Operators). - Native
$jsonSchema: Query filtering and write-time validation via SQLite CHECK constraints. - Window Functions: Complete MongoDB 5.0+ suite (
$rank,$top,$bottom, math operators). - MongoDB-compatible ObjectId: Full 12-byte specification with automatic generation.
- Full GridFS Support: Modern
GridFSBucketAPI plus legacyGridFScompatibility. - Binary Data: PyMongo-compatible
Binaryclass with UUID support. - AutoVacuum & compact: Reclaim disk space with incremental or full VACUUM.
- dbStats Command: MongoDB-compatible statistics with accurate index sizes.
- SQL Translation Caching: 10-30% faster for repeated aggregation pipelines and
$exprqueries. - Configurable Journal Mode: WAL (default), DELETE, MEMORY, and more.
- Security Hardening: Built-in SQL injection protection via centralized identifier quoting.
See Release Notes for the full history.
Latest Release: v1.19.0
NeoSQLite v1.19.0 is a feature and correctness release covering every change since v1.18.1: 28 audited issue fixes (#183–#210), new aggregation/query capabilities, persistent validators, sandboxed JavaScript engines, and a hardened NX‑27017 wire server. The minimum supported Python version remains 3.12.
Key Highlights:
- New SQL capabilities —
$metacompilation, BSON-aware_idranges, Tier‑2 hybrid stage evaluation,$indexStats, and$set/$sortByCountaliases. - Persistent validators —
$jsonSchemarules survive reconnection and are enforced through both the direct API and NX‑27017createCollection. - Sandboxed JavaScript — pluggable out-of-process engines (
jsboxpreferred, patched Node.js fallback) with scrubbed environments and bounded resources for$function/$where. - Correctness audit — transactions, SQL quoting, indexing, TTL, GridFS, ChangeStream, cursors, updates, expression evaluators, wire protocol, and value-type validation were cross-checked against MongoDB.
- MongoDB-verified — both differential suites report 100% compatibility (452 checks each), with 3,446 unit tests passing.
- Tier routing preserved — fixed operations still execute in SQL Tier 1/2; only ambiguous numeric dotted paths deliberately use Tier 3.
Behavior changes include MongoDB-correct $bucketAuto boundaries, InvalidOperation on rewind() of a closed cursor, and strict daemon PID identity checks. For full details, see documents/releases/v1.19.0.md. Previous release highlights are in documents/releases/v1.18.1.md.
Installation
NeoSQLite supports Python 3.12, 3.13, 3.14, and 3.15.
SQLite 3.26+ is supported. JSONB, aggregate ORDER BY, RETURNING, and the
3.35+ math functions are used when available; older SQLite builds fall back to
the Python tier or register compatible SQL functions automatically.
The optional JavaScript operators ($function, $where) run inside a
sandboxed child process using either jsbox
(QuickJS, preferred, install via pip install "neosqlite[js]") or a
patched external Node.js executable on PATH (fallback). See
JavaScript Operators for engine selection and
special-platform installation instructions.
pip install neosqlite
Optional Extras
# Sandboxed JavaScript operators ($function, $where) via jsbox (QuickJS, preferred)
pip install "neosqlite[js]"
# Enhanced JSON/JSONB support (only needed if your SQLite lacks JSON functions)
pip install neosqlite[jsonb]
# Memory-constrained processing for large result sets
pip install neosqlite[memory-constrained]
# NX-27017 MongoDB Wire Protocol Server
pip install "neosqlite[nx27017]" # Core
pip install "neosqlite[nx27017-speed]" # With uvloop (Linux/macOS)
The
jsonbextra installspysqlite3-binaryonly on Linux x86_64 with Python< 3.15, where upstream publishesmanylinux_x86_64wheels (cp312–cp314). On Python 3.15, macOS, Windows, or ARM the extra installs no additional driver; the standard library SQLite is used.
Migrating legacy _id TEXT databases
Databases created by NeoSQLite 1.17.4 and earlier on non-JSONB SQLite store
_id values in a TEXT column. That loses the distinction between values such
as integer 1 and string "1". The migration command copies the database to a
new file and rebuilds those collection tables with _id BLOB:
neosqlite-migration old.db new.db
The source file is never modified. Use --dry-run to list affected tables,
and --overwrite to replace an existing destination atomically. After the
migration succeeds, point the application at new.db. The command preserves
collection indexes and triggers; tables with foreign keys, extra columns, or
non-standard schemas are left untouched.
Quickstart
import neosqlite
with neosqlite.Connection(':memory:') as conn:
users = conn.users
# Insert
users.insert_one({'name': 'Alice', 'age': 30})
users.insert_many([
{'name': 'Bob', 'age': 25},
{'name': 'Charlie', 'age': 35}
])
# Find
alice = users.find_one({'name': 'Alice'})
for user in users.find():
print(user)
# Update
users.update_one({'name': 'Alice'}, {'$set': {'age': 31}})
# Delete & Count
result = users.delete_many({'age': {'$gt': 30}})
print(f"Remaining: {users.count_documents({})}")
Drop-in Replacement for PyMongo
1. Direct API (No MongoDB)
import neosqlite
client = neosqlite.Connection('mydatabase.db')
collection = client.mycollection
collection.insert_one({"name": "test"})
2. Wire Protocol (NX-27017) — Zero Code Changes
# Start server
nx-27017 --db ./myapp.db
# Then use PyMongo normally — no code changes!
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
collection = client.mydatabase.mycollection
collection.insert_one({"name": "test"}) # Works!
PyMongo Compatibility
| Metric | Result |
|---|---|
| Total Tests | 439 |
| Passed | 420 |
| Skipped | 19 (architectural differences) |
| Failed | 0 |
| Compatibility | 100% |
Skipped tests are due to MongoDB requiring a replica set (change streams, transactions), NeoSQLite extensions ($log2, $contains), or JavaScript operators when no supported JS engine (jsbox or patched Node.js) is installed. All comparable APIs pass. Tested against MongoDB 8.x (mongo:8.2.12 pinned container image).
Run the comparison yourself: ./scripts/run-api-comparison.sh
_id Field Behavior
NeoSQLite uses a strict MongoDB-compatible _id column:
- Integer
_idvalues are stored and queried in the dedicated_idcolumn — not redirected to the auto-incrementidrowid. - String
_idvalues are kept verbatim (e.g.,"5"is a string, not converted to integer5). - Auto-generated
_idproduces MongoDB-compatible 12-byte ObjectIds stored in the_idcolumn. - Legacy collections (created before the
_idcolumn existed) fall back to theidcolumn via an automatic resolver. - Range queries (
$gt,$lt, etc.) on_idare compiled to native SQL with BSON type guards, so only values of the operand's BSON type match — matching MongoDB semantics without a Python fallback.
Key APIs
Indexes
# Single-key, compound, nested
users.create_index('age')
users.create_index([('name', neosqlite.ASCENDING), ('age', neosqlite.DESCENDING)])
users.create_index('profile.followers')
# FTS5 text search
users.create_search_index('bio')
Query Operators
$eq, $gt, $gte, $lt, $lte, $ne, $in, $nin, $and, $or, $not, $nor,
$exists, $type, $regex, $elemMatch, $size, $mod,
$bitsAllSet, $bitsAllClear, $bitsAnySet, $bitsAnyClear,
$text (FTS5), $jsonSchema, and $where (JavaScript, sandboxed via jsbox or Node.js — see below).
JavaScript Operators
The $function aggregation expression and the $where query predicate execute
JavaScript in an isolated out-of-process sandbox communicating over
JSON-lines IPC (never pickle). Because the JS engine runs in a separate child
OS process—and jsbox's native extension is never loaded into the host Python
process—any C-level memory corruption, segfault, out-of-memory crash, or
uninterruptible native operation inside the JS engine is strictly contained to
the disposable worker process and cannot affect the main NeoSQLite engine or
SQLite database.
Supported Engines & Default Priority
NeoSQLite supports pluggable JavaScript engines and selects jsbox over
node by default (engine="auto"):
| Engine | Backend | Default Priority | How to Enable |
|---|---|---|---|
jsbox (preferred) |
Embedded QuickJS via Rust/PyO3 in an isolated python -I subprocess |
1 (preferred) | pip install "neosqlite[js]" |
node (fallback) |
External Node.js (--permission + per-call vm.createContext) |
2 (fallback) | Install a patched Node.js on PATH |
When using the node engine, only patched, supported release lines are
accepted:
| Node.js line | Minimum patched version |
|---|---|
| 22.x (Maintenance LTS) | 22.23.5 |
| 24.x (Active LTS) | 24.22.3 |
| 26.x (LTS, preferred) | 26.13.1 |
EOL lines (18, 20, odd-numbered 21/23/25, and older) and unpatched releases of active lines are rejected. These minimums address CVE-2026-111497 ("Node2Shell") and the November 2026 HTTP/2 and TLS security fixes.
If neither
jsboxnor a vetted Node.js binary is available (or if JavaScript is disabled withengine="none"),$functionand$whereraiseNotImplementedErrorexplaining why each engine is unavailable. No other functionality is affected.
import neosqlite
# Uses jsbox when installed (neosqlite[js]), otherwise falls back to patched Node.js
docs.aggregate([
{"$addFields": {
"total": {
"$function": {
"body": "function(a, b) { return a * b; }",
"args": ["$price", "$qty"],
"lang": "js",
}
}
}}
])
docs.find({"$where": "this.price > 100"})
Selecting or Disabling a JS Engine
Select an engine programmatically or via the NEOSQLITE_JS_ENGINE environment
variable (auto, jsbox, node, none, or any custom engine registered via
neosqlite.js.register_js_engine):
import neosqlite
# Inspect detected engines in priority order
for engine in neosqlite.list_js_engines():
print(engine.name, engine.available, engine.version, engine.detail)
# Pin a specific engine (does not silently fall back if unavailable)
neosqlite.set_js_engine("jsbox") # Require QuickJS (jsbox)
neosqlite.set_js_engine("node") # Require patched Node.js (V8 JIT)
neosqlite.set_js_engine("none") # Disable $function and $where completely
neosqlite.set_js_engine("auto") # Default: prefer jsbox, fall back to node
# Scoped override for a single block
with neosqlite.use_js_engine("node"):
rows = list(docs.find({"$where": "this.price > 100"}))
# Override engine selection via environment variable
NEOSQLITE_JS_ENGINE=jsbox python myapp.py
NEOSQLITE_JS_ENGINE=node python myapp.py
NEOSQLITE_JS_ENGINE=none python myapp.py
Sandbox Guarantees
- Process & memory isolation: Both
jsboxandnoderun in dedicated child processes with a scrubbed environment (env={}on Linux/macOS; onlySYSTEMROOT/SYSTEMDRIVE/WINDIRon Windows) so parent secrets never enter the worker. Workers that crash or hit OOM are automatically restarted. - Zero ambient authority & per-call realm isolation: Each evaluation runs
in a fresh JS realm (
jsbox.Runtime()/vm.createContext(Object.create(null))) with noprocess,env,require, filesystem, network, or timer access and no cross-call prototype/global leakage. - Resource & timeout limits: Each call is bounded by a 5-second timeout
(with hard
SIGKILLescalation by the supervisor), engine heap caps (64 MB default forjsbox; 512 MB V8 heap fornode), and LinuxRLIMIT_AScaps (512 MB forjsbox; 4096 MB fornode). Workers shut down automatically at interpreter exit (or explicitly vianeosqlite.close_js_workers()). - Scope: Only
$functionand$whereuse the JS worker;$accumulatorand Atlas-only$scriptremain unsupported.
Installing jsbox on Special (sdist) Platforms
Prebuilt cp310-abi3 wheels for jsbox are published on PyPI for standard
(GIL-enabled) CPython 3.12–3.15 on:
- Linux:
x86_64andaarch64(manylinuxandmusllinux) - macOS:
arm64(Apple Silicon, macOS 11+) - Windows:
amd64
On these platforms, pip install "neosqlite[js]" installs a ~0.7 MB wheel with
no compiler or Rust toolchain needed.
For platforms without a prebuilt wheel (such as Intel macOS x86_64 or
Windows arm64), pip falls back to building jsbox from its source
distribution (sdist):
-
Install build prerequisites:
- Rust toolchain (
rustup/cargo): https://rustup.rs/ - C compiler: Xcode Command Line Tools (
xcode-select --install) on macOS, Visual Studio C++ Build Tools on Windows, orgcc/clangon Linux.
- Rust toolchain (
-
Install on Python 3.12–3.14:
pip install "neosqlite[js]"
-
Install from sdist on Python 3.15:
jsbox 0.1.3pinspyo3 = "0.27", whose build-time check caps native compilation at Python 3.14. Enable Stable ABI forward compatibility so Cargo builds cleanly against theabi3-py310limited C API:# macOS / Linux (Intel Mac, non-wheel Linux arches) PYO3_USE_ABI3_FORWARD_COMPATIBILITY=1 pip install "neosqlite[js]"
# Windows PowerShell (Windows ARM64) $env:PYO3_USE_ABI3_FORWARD_COMPATIBILITY = "1" pip install "neosqlite[js]"
-
Free-threaded CPython (
3.13t/3.14t/3.15t): Traditionalabi3wheels cannot be loaded by free-threaded builds. Install coreneosqlitewithout[js]and use a patched Node.js binary onPATH(automatic fallback underengine="auto", or explicitNEOSQLITE_JS_ENGINE=node).
Aggregation Stages
$match, $project, $group, $sort, $skip, $limit, $unwind,
$lookup, $facet, $bucket, $bucketAuto, $sample, $merge,
$setWindowFields, $graphLookup, $fill, $densify, $unionWith,
$replaceRoot, $replaceWith, $unset, $count, $redact, $addFields, $switch,
$set (alias for $addFields), $sortByCount, $indexStats (MongoDB-shaped index metadata).
Transactions
with client.start_session() as session:
with session.start_transaction():
users.insert_one({"name": "Alice"}, session=session)
orders.insert_one({"user": "Alice"}, session=session)
# Commits on success, rolls back on exception
Change Streams
# Native SQLite triggers — no replica set needed
stream = collection.watch()
for change in stream:
print(change)
Journal Mode
from neosqlite import Connection, JournalMode
db = Connection("app.db", journal_mode=JournalMode.WAL) # Default
| Mode | Use Case |
|---|---|
| WAL | Best concurrency (default) |
| DELETE | Single-file distribution |
| MEMORY | Maximum speed, no crash recovery |
Documentation
| Topic | Link |
|---|---|
| Knowledge Base / Docs | documents/ |
| Release Notes | documents/releases/ |
| GridFS | documents/gridfs.md |
| Text Search | documents/text-search.md |
| Aggregation Optimization | documents/aggregation-pipeline-optimization.md |
| NX-27017 Server | packages/nx_27017/README.md |
| API Comparison | examples/api_comparison/README.md |
Contributing
Clone the repository:
git clone https://github.com/cwt/neosqlite.git
cd neosqlite
Create and activate a virtual environment:
python3 -m venv .venv
source .venv/bin/activate
Then run the test script, which installs all required dependencies automatically:
./scripts/runtest.sh
Shell Script Compatibility
All shell scripts in this project target bash 3.2+ for compatibility with macOS, which still ships with bash 3.2.x. Please ensure any contributions to shell scripts remain compatible.
Contribution and License
This project was originally developed as shaunduncan/nosqlite and was later forked as plutec/nosqlite before becoming NeoSQLite. It is now maintained by Chaiwat Suttipongsakul and is licensed under the MIT license.
Contributions are highly encouraged. If you find a bug, have an enhancement in mind, or want to suggest a new feature, please feel free to open an issue or submit a pull request.
Metadata
Release files for neosqlite 1.19.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| neosqlite-1.19.0.tar.gz | 503.3 kB | Without provenance | Details for neosqlite-1.19.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| neosqlite-1.19.0-py3-none-any.whl | Python 3 | none | any | Details for neosqlite-1.19.0-py3-none-any.whl |
Total release size: 1.1 MB
Release files / neosqlite-1.19.0.tar.gz
| Download URL | neosqlite-1.19.0.tar.gz |
|---|---|
| Size | 503.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d49d70435a0ad4711207ce5598ee0b6aed5beb709214ecfb9f0d249fcd82dd1a
|
|
BLAKE2b-256 checksum How to use checksums |
8d02a286694689ec92ce16d34e4b3f32a96c4003d37735fe49f2981b21bbeaaf
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.5.1 CPython/3.14.10 Linux/7.3.4-200.fc44.x86_64
|
Release files / neosqlite-1.19.0-py3-none-any.whl
| Download URL | neosqlite-1.19.0-py3-none-any.whl |
|---|---|
| Size | 579.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
afdb26bac2363b3041c4da3d8c82faaf901a553e03abf106f8a2a16460c5275e
|
|
BLAKE2b-256 checksum How to use checksums |
b9f6273112c362b918a1d7809aadb21a1cc1c45426ae1455b09832a80e9f9389
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
poetry/2.5.1 CPython/3.14.10 Linux/7.3.4-200.fc44.x86_64
|
Security for neosqlite 1.19.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.