mongo.do
v0.1.1
Published
MongoDB-compatible database backed by Cloudflare Durable Objects SQLite
Maintainers
Readme
MondoDB
MongoDB on the Edge — A MongoDB-compatible database that runs entirely on Cloudflare Workers, with native AI agent support, vector search, and real-time analytics.
Why MondoDB?
Traditional databases require infrastructure management, connection pooling, and careful scaling. MondoDB eliminates all of that by running directly on Cloudflare's edge network:
- Zero Infrastructure — No servers to manage, no connection limits, no cold starts
- Global by Default — Data lives at the edge, close to your users
- MongoDB Compatible — Drop-in replacement for most MongoDB operations
- AI-Native — Built-in support for AI agents, vector search, and LLM tool calling
- Serverless Economics — Pay only for what you use, scale to zero
import { MongoClient } from 'mongo.do'
const client = new MongoClient('https://your-worker.workers.dev')
const db = client.db('myapp')
const users = db.collection('users')
// It's just MongoDB
await users.insertOne({ name: 'Alice', email: '[email protected]' })
const user = await users.findOne({ email: '[email protected]' })Features
Core Database
| Feature | Description |
|---------|-------------|
| CRUD Operations | insertOne, insertMany, find, findOne, updateOne, updateMany, deleteOne, deleteMany, replaceOne, bulkWrite |
| Aggregation Pipeline | 20+ stages including $match, $group, $lookup, $unwind, $facet, $bucket, $graphLookup |
| Indexing | Single-field, compound, text, geospatial (2dsphere), TTL, and unique indexes |
| Transactions | Multi-document ACID transactions with startSession() and withTransaction() |
| Change Streams | Real-time notifications via collection.watch() |
AI & Agents
| Feature | Description |
|---------|-------------|
| Vector Search | Semantic similarity search powered by Cloudflare Vectorize with automatic embeddings |
| Full-Text Search | FTS5-powered $search stage with scoring, highlights, and fuzzy matching |
| AgentFS | Virtual filesystem for AI agents with glob, grep, KV store, and immutable audit logs |
| MCP Protocol | Model Context Protocol server with Anthropic and Vercel AI SDK adapters |
| $function Operator | Execute sandboxed JavaScript in aggregation pipelines |
Connectivity
| Feature | Description | |---------|-------------| | Wire Protocol | Connect with MongoDB Compass, mongosh, and native drivers via TCP | | HTTP/RPC | JSON-RPC over HTTP with batching and request deduplication | | WebSocket | Persistent connections for real-time applications | | Service Bindings | Zero-latency Worker-to-Worker communication |
Developer Experience
| Feature | Description |
|---------|-------------|
| Studio UI | Web-based database browser with query editor and document management |
| CLI Server | Local development with npx mongo.do serve --backend sqlite |
| TypeScript | Full type definitions with generics support |
Quick Start
Install
npm install mongo.doDeploy to Cloudflare Workers
// src/index.ts
import { MondoEntrypoint, MondoDatabase } from 'mongo.do'
export { MondoDatabase }
export default MondoEntrypoint// wrangler.jsonc
{
"name": "my-mongo.do",
"main": "src/index.ts",
"compatibility_date": "2025-01-01",
"compatibility_flags": ["nodejs_compat"],
"durable_objects": {
"bindings": [{ "name": "MONDO_DATABASE", "class_name": "MondoDatabase" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MondoDatabase"] }]
}npx wrangler deployLocal Development
# Start a local server with SQLite backend
npx mongo.do serve --port 27017 --backend sqlite
# Connect with mongosh
mongosh mongodb://localhost:27017/mydbExamples
Vector Search (Semantic Similarity)
// Create a vector index
await collection.createIndex({ embedding: 'vector' }, {
vectorOptions: { dimensions: 1024, metric: 'cosine' }
})
// Search by similarity
const results = await collection.aggregate([
{
$vectorSearch: {
queryVector: await getEmbedding('machine learning tutorials'),
path: 'embedding',
numCandidates: 100,
limit: 10
}
},
{ $project: { title: 1, score: { $meta: 'vectorSearchScore' } } }
]).toArray()Full-Text Search
// Create a text index
await collection.createIndex({ title: 'text', content: 'text' })
// Search with scoring
const results = await collection.aggregate([
{
$search: {
text: { query: 'serverless database', path: ['title', 'content'] },
highlight: { path: 'content' }
}
}
]).toArray()AI Agent with MCP
import { createMcpServer, createAnthropicAdapter } from 'mongo.do/mcp'
import Anthropic from '@anthropic-ai/sdk'
const server = createMcpServer({ dbAccess })
const adapter = createAnthropicAdapter({ server })
await adapter.initialize()
const client = new Anthropic()
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
tools: await adapter.getTools(),
messages: [{ role: 'user', content: 'Find all orders over $1000' }]
})AgentFS — Virtual Filesystem for AI
import { MonDoAgent } from 'mongo.do/agentfs'
const agent = new MonDoAgent(db)
// Glob pattern matching
const files = await agent.glob('src/**/*.ts')
// Content search
const matches = await agent.grep('TODO', { path: 'src/', type: 'ts' })
// Key-value store with TTL
await agent.kv.set('session:123', { user: 'alice' }, { ttl: 3600 })
// Immutable audit log
await agent.auditLog.append({
action: 'file_read',
path: '/src/index.ts',
agent: 'claude'
})Real-Time Change Streams
const changeStream = collection.watch([
{ $match: { operationType: { $in: ['insert', 'update'] } } }
])
for await (const change of changeStream) {
console.log('Change detected:', change.operationType, change.documentKey)
await notifySubscribers(change)
}Transactions
const session = client.startSession()
await session.withTransaction(async () => {
await accounts.updateOne({ userId: 'alice' }, { $inc: { balance: -100 } }, { session })
await accounts.updateOne({ userId: 'bob' }, { $inc: { balance: 100 } }, { session })
})Geospatial Queries
// Create 2dsphere index
await places.createIndex({ location: '2dsphere' })
// Find nearby locations
const nearby = await places.find({
location: {
$near: {
$geometry: { type: 'Point', coordinates: [-73.97, 40.77] },
$maxDistance: 5000 // 5km
}
}
}).toArray()Architecture
┌─────────────────────────────────────────────────────────────────────────┐
│ Client Applications │
├─────────────────┬─────────────────┬─────────────────┬───────────────────┤
│ MongoDB │ HTTP/RPC │ WebSocket │ Service Binding │
│ Wire Protocol │ JSON-RPC │ Real-time │ Worker-to-Worker │
├─────────────────┴─────────────────┴─────────────────┴───────────────────┤
│ MondoDB Worker (Edge) │
├─────────────────────────────────────────────────────────────────────────┤
│ Query Translator │ Aggregation Engine │ MCP Server │ AgentFS │
├─────────────────────────────────────────────────────────────────────────┤
│ Durable Objects (SQLite Storage) │
├──────────────────────────┬──────────────────────────────────────────────┤
│ Vectorize │ R2 / OLAP (Coming Soon) │
│ (Vector Embeddings) │ (ClickHouse, Iceberg, Data Catalog) │
└──────────────────────────┴──────────────────────────────────────────────┘MondoDB translates MongoDB queries to SQLite at runtime:
- Query Translation — MongoDB operators → SQLite SQL with full expression support
- Durable Object Storage — Each database runs as an isolated Durable Object with SQLite
- Edge Execution — Queries execute at the edge, close to your users
- Optional Integrations — Vectorize for embeddings, R2 for large objects, ClickHouse for analytics
Connectivity Options
Wire Protocol (MongoDB Compatible)
Connect using MongoDB Compass, mongosh, or any MongoDB driver:
# Local development
npx mongo.do serve --port 27017
# Connect with mongosh
mongosh mongodb://localhost:27017/mydb
# Connect with Compass
# Use connection string: mongodb://localhost:27017HTTP RPC
// Direct HTTP calls
const response = await fetch('https://your-worker.workers.dev/rpc', {
method: 'POST',
body: JSON.stringify({
method: 'find',
params: ['mydb', 'users', { active: true }]
})
})
// Batch requests
const batch = await fetch('https://your-worker.workers.dev/rpc/batch', {
method: 'POST',
body: JSON.stringify([
{ id: '1', method: 'find', params: ['mydb', 'users', {}] },
{ id: '2', method: 'count', params: ['mydb', 'orders', {}] }
])
})Service Bindings (Zero Latency)
// In your consuming worker
export default {
async fetch(request: Request, env: Env) {
const users = await env.MONDO.find('mydb', 'users', { active: true })
return Response.json(users)
}
}Configuration
With Vector Search
{
"vectorize": {
"bindings": [{ "binding": "VECTORIZE", "index_name": "embeddings" }]
},
"ai": { "binding": "AI" },
"vars": {
"EMBEDDING_MODEL": "@cf/baai/bge-m3",
"EMBEDDING_ENABLED": "true"
}
}With $function Operator
{
"compatibility_flags": ["nodejs_compat", "enable_ctx_exports"],
"worker_loaders": [{ "binding": "LOADER" }]
}Documentation
Comprehensive guides are available at docs/:
| Guide | Description | |-------|-------------| | CRUD Operations | Insert, find, update, delete operations | | Aggregation | Pipeline stages and expressions | | Vector Search | Semantic similarity with Vectorize | | Full-Text Search | FTS5-powered text search | | AgentFS | Virtual filesystem for AI agents | | MCP Protocol | Model Context Protocol integration | | Wire Protocol | MongoDB-compatible TCP server | | Transactions | Multi-document ACID transactions | | Change Streams | Real-time change notifications | | Geospatial | Location-based queries | | Indexing | Index types and optimization | | Analytics Layer | ClickHouse, Iceberg, CDC streaming | | Studio UI | Web-based database browser | | CLI Server | Local development server | | Cloudflare Workers | Deployment guide |
Analytics Layer
MondoDB includes an integrated analytics layer for OLAP workloads:
// Route analytical queries to ClickHouse via $analytics
const revenue = await orders.aggregate([
{
$analytics: {
pipeline: [
{ $match: { createdAt: { $gte: lastMonth } } },
{ $group: { _id: '$category', total: { $sum: '$amount' } } },
{ $sort: { total: -1 } }
]
}
}
]).toArray()| Component | Description | |-----------|-------------| | $analytics Stage | Route queries to ClickHouse for analytical workloads | | CDC Streaming | Real-time change data capture via Cloudflare Pipelines | | Apache Iceberg | Open table format with time travel and schema evolution | | R2 Data Catalog | Schema registry and table metadata on R2 |
See the Analytics Layer Guide for details.
Roadmap
Coming Soon
- Multi-Region — Cross-region replication with conflict resolution
- Sharding — Horizontal partitioning for very large datasets
Development
# Install dependencies
npm install
# Run tests
npm test
# Build
npm run build
# Local development
npm run devLicense
MIT — see LICENSE
Contributing
Contributions welcome! Please open an issue or submit a pull request.
