Skip to content

Tutorial: Using HeliosDB's MongoDB Protocol

Tutorial: Using HeliosDB’s MongoDB Protocol

Level: Intermediate | Time: 20 minutes | Version: 7.2.0

HeliosDB implements 50+ MongoDB aggregation stages and full wire protocol compatibility. Connect with mongosh, drivers, or any MongoDB client — no code changes needed.

Start with MongoDB Enabled

Terminal window
heliosdb-full --enable-mongodb --mongodb-port 27017

Connect with mongosh

Terminal window
mongosh --host localhost --port 27017

You’ll see:

HeliosDB MongoDB-compatible server

Basic CRUD Operations

Insert Documents

// Switch to a database
use myapp
// Insert a single document
db.users.insertOne({
name: "Alice",
email: "alice@example.com",
age: 30,
tags: ["admin", "developer"],
address: { city: "Berlin", country: "DE" }
})
// Insert multiple documents
db.users.insertMany([
{ name: "Bob", email: "bob@example.com", age: 25, tags: ["developer"] },
{ name: "Carol", email: "carol@example.com", age: 35, tags: ["manager"] },
{ name: "Dave", email: "dave@example.com", age: 28, tags: ["developer", "devops"] }
])

Query Documents

// Find all documents
db.users.find()
// Find with filter
db.users.find({ age: { $gte: 30 } })
// Find with projection (select specific fields)
db.users.find({ tags: "developer" }, { name: 1, email: 1, _id: 0 })
// Complex query with logical operators
db.users.find({
$or: [
{ age: { $lt: 26 } },
{ tags: "admin" }
]
})
// Count documents
db.users.countDocuments({ tags: "developer" })
// Distinct values
db.users.distinct("address.country")

Update Documents

// Update one document
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 31 }, $addToSet: { tags: "lead" } }
)
// Update multiple documents
db.users.updateMany(
{ tags: "developer" },
{ $set: { department: "engineering" } }
)

Delete Documents

// Delete one document
db.users.deleteOne({ name: "Dave" })
// Delete matching documents
db.users.deleteMany({ age: { $lt: 26 } })

Aggregation Pipeline

HeliosDB supports 50+ aggregation stages — more than FerretDB.

Basic Aggregation

// Group by tag, count users per tag
db.users.aggregate([
{ $unwind: "$tags" },
{ $group: { _id: "$tags", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])

Multi-Stage Pipeline

// Complex analytics: users per country with average age
db.users.aggregate([
{ $match: { age: { $gte: 25 } } },
{ $group: {
_id: "$address.country",
avg_age: { $avg: "$age" },
count: { $sum: 1 },
users: { $push: "$name" }
}},
{ $sort: { count: -1 } },
{ $project: {
country: "$_id",
avg_age: { $round: ["$avg_age", 1] },
count: 1,
users: 1,
_id: 0
}}
])

$lookup (Join)

// Create orders collection
db.orders.insertMany([
{ user: "Alice", product: "Widget", amount: 29.99 },
{ user: "Alice", product: "Gadget", amount: 49.99 },
{ user: "Bob", product: "Widget", amount: 29.99 }
])
// Join users with their orders
db.users.aggregate([
{ $lookup: {
from: "orders",
localField: "name",
foreignField: "user",
as: "orders"
}},
{ $project: {
name: 1,
order_count: { $size: "$orders" },
total_spent: { $sum: "$orders.amount" }
}}
])

$facet (Multiple Aggregations in One)

db.users.aggregate([
{ $facet: {
"by_age": [
{ $bucket: {
groupBy: "$age",
boundaries: [20, 25, 30, 35, 40],
default: "40+",
output: { count: { $sum: 1 } }
}}
],
"by_tag": [
{ $unwind: "$tags" },
{ $sortByCount: "$tags" }
],
"summary": [
{ $group: {
_id: null,
total: { $sum: 1 },
avg_age: { $avg: "$age" }
}}
]
}}
])

AI-Native Commands

These commands are unique to HeliosDB — no MongoDB server or FerretDB has them.

// Create a collection with embeddings
db.articles.insertMany([
{ title: "Intro to AI", content: "...", embedding: [0.1, 0.2, 0.3, 0.4] },
{ title: "Database Design", content: "...", embedding: [0.5, 0.1, 0.2, 0.3] },
{ title: "ML Pipelines", content: "...", embedding: [0.15, 0.25, 0.35, 0.45] }
])
// Search for similar vectors (Atlas Search compatible syntax)
db.runCommand({
vectorSearch: "articles",
queryVector: [0.12, 0.22, 0.32, 0.42],
path: "embedding",
numCandidates: 100,
limit: 5
})

Natural Language Queries

// Ask questions in plain English
db.runCommand({
nlQuery: "show me all users who signed up last week in Europe and haven't logged in since"
})
// Returns: translated MongoDB query + SQL equivalent
// In production, executes via heliosdb-nl NL2SQL engine

Schema Analysis

// Get AI-powered schema optimization recommendations
db.runCommand({ schemaAnalyze: "users" })
// Returns:
// - Document count and average size
// - Schema consistency score
// - Normalization suggestions
// - Index recommendations
// - Data type optimization tips

Intelligent Index Recommendations

// Get index suggestions based on query patterns
db.runCommand({ indexRecommend: "users" })
// Returns:
// - Recommended indexes from observed query patterns
// - Cost-based ranking (estimated improvement per index)
// - What-if simulation results
// - Auto-apply option: APPLY INDEX RECOMMENDATION id (via SQL)

Anomaly Detection

// Detect anomalies in collection data
db.runCommand({
aiAnomaly: "metrics",
field: "response_time"
})
// Returns: anomaly status, models used, z-score, thresholds

AI Engine Status

// Check all AI capabilities
db.runCommand({ aiStatus: 1 })
// Returns: vector_search, full_text_search, rag_pipeline,
// nl2sql, anomaly_detection, ml_tiering, autonomous_agents,
// embedding_providers, intelligent_indexing

Admin Commands

// Database statistics
db.runCommand({ dbStats: 1 })
// Collection statistics
db.runCommand({ collStats: "users" })
// Current operations
db.runCommand({ currentOp: 1 })
// Server status
db.runCommand({ serverStatus: 1 })
// List databases
db.adminCommand({ listDatabases: 1 })
// List collections
db.runCommand({ listCollections: 1 })

Transactions (Multi-Document ACID)

// Start a session
const session = db.getMongo().startSession()
// Start transaction
session.startTransaction()
try {
const users = session.getDatabase("myapp").users
const orders = session.getDatabase("myapp").orders
// Atomic multi-collection update
users.updateOne(
{ name: "Alice" },
{ $inc: { balance: -29.99 } },
{ session }
)
orders.insertOne(
{ user: "Alice", product: "Widget", amount: 29.99, date: new Date() },
{ session }
)
// Commit atomically
session.commitTransaction()
} catch (e) {
session.abortTransaction()
throw e
}

GridFS (Large File Storage)

// Store large files (>16MB) using GridFS
const bucket = new GridFSBucket(db, { bucketName: "attachments" })
// Upload (from Node.js driver)
const uploadStream = bucket.openUploadStream("report.pdf", {
contentType: "application/pdf",
metadata: { department: "finance", year: 2026 }
})
// Download
const downloadStream = bucket.openDownloadStreamByName("report.pdf")

Migration from MongoDB

Step 1: Point Connection String

// Before (MongoDB)
const uri = "mongodb://user:pass@mongodb-host:27017/myapp"
// After (HeliosDB) — just change the host
const uri = "mongodb://user:pass@heliosdb-host:27017/myapp"

Step 2: Verify

Terminal window
# mongosh connects the same way
mongosh --host heliosdb-host --port 27017
# Test basic operations
db.test.insertOne({ hello: "world" })
db.test.find()

Step 3: Use AI Features

// These work only on HeliosDB — bonus features, no code changes needed
db.runCommand({ aiStatus: 1 })
db.runCommand({ vectorSearch: "collection", queryVector: [...], limit: 10 })
db.runCommand({ nlQuery: "find inactive premium users" })

Cross-Protocol Queries

The same data is accessible from all 14 protocols:

Terminal window
# Via MongoDB
mongosh -c 'db.users.find({ age: { $gte: 30 } })'
# Via PostgreSQL (same data, SQL syntax)
psql -c "SELECT * FROM users WHERE age >= 30"
# Via Redis
redis-cli VSEARCH user_embeddings 5 0.1 0.2 0.3
# Via REST API
curl http://localhost:8443/api/v1/tables

What’s Next