Documentation

AI Assistant

AI Assistant

Use AI to generate MongoDB queries, build aggregation pipelines, translate SQL to MongoDB, and analyze your database schema. Describe what you need in plain English and let AI write the MongoDB code for you. VisuaLeaf ships with pluggable providers (OpenAI, Anthropic, Google Vertex AI, and Ollama for fully local inference), so you can pick the model that best matches your accuracy, cost, and privacy requirements.

Quick Start

Generate your first AI-powered query:

  1. Open Settings → AI Assistant and choose a provider (OpenAI, Anthropic, Google Vertex AI, or Ollama)
  2. Paste your API key (or point Ollama at your local endpoint) and pick a model
  3. Click the AI Assistant button in the toolbar or sidebar
  4. Select your target collection
  5. Type your request in plain English (e.g., "Find all users who signed up this month with active subscriptions")
  6. Review the generated MongoDB query
  7. Click "Use Query" to apply it to the Query Builder, Aggregation Builder, or Shell
AI Assistant interface showing chat panel and generated query

Supported AI Providers

The AI Assistant is built on Spring AI 1.0.0, giving you a single, consistent UI across four provider families. All four ship in every VisuaLeaf install — you only enable the ones you want to use.

Provider Models Best For Credentials
OpenAI gpt-4, gpt-4o, gpt-4o-mini, o1 Broadly reliable query generation, cost-effective with gpt-4o-mini OpenAI API key
Anthropic claude-opus-4, claude-sonnet-4, claude-haiku-4 Long-context schema analysis, precise pipeline reasoning Anthropic API key
Google Vertex AI Gemini 2.0 & Gemini 2.5 series Enterprise Google Cloud deployments, multimodal use cases GCP project + service account JSON
Ollama llama3, mistral, phi3, any Ollama-compatible model Fully local / air-gapped environments; zero data leaves your machine Local Ollama endpoint (e.g., http://localhost:11434)

Bring your own key. All API keys are stored per user and used to talk directly to the chosen provider — VisuaLeaf servers never proxy or see your prompts, completions, or keys. For teams that require complete network isolation, run Ollama locally and select it as the provider.

AI Query Generation

Generate MongoDB find queries from natural language descriptions. Perfect for complex filters, date ranges, and multi-condition queries.

AI generating a MongoDB query from natural language input

Query Examples

Natural Language Generated Query
"Find users with verified email" { emailVerified: true }
"Get orders over $100 from last week" { total: { $gt: 100 }, createdAt: { $gte: ISODate("...") } }
"Find products with stock less than 10" { stock: { $lt: 10 } }
"Show customers from New York or California" { state: { $in: ["NY", "CA"] } }

Query Generation Features

  • Schema-Aware: AI understands your collection schema and suggests valid field names
  • Date Handling: Automatically converts date references like "last month" or "this year"
  • Operator Selection: Chooses appropriate operators ($gt, $lt, $in, $regex, etc.)
  • Nested Fields: Supports queries on nested document fields
  • Array Queries: Handles array field queries with $elemMatch, $all, etc.

SQL to MongoDB Translation

Migrating from PostgreSQL, MySQL, or SQL Server? Paste a SQL statement and the AI Assistant rewrites it as an equivalent MongoDB find() call or aggregation pipeline. Great for developers still building MongoDB muscle memory.

-- Input (SQL)
SELECT country, COUNT(*) AS orders
FROM  orders
WHERE created_at >= NOW() - INTERVAL '30 days'
GROUP BY country
ORDER BY orders DESC
LIMIT 10;

// Output (MongoDB aggregation)
db.orders.aggregate([
  { $match: { created_at: { $gte: ISODate("...") } } },
  { $group: { _id: "$country", orders: { $sum: 1 } } },
  { $sort:  { orders: -1 } },
  { $limit: 10 }
]);

AI Aggregation Pipelines

Build complex aggregation pipelines by describing your data transformation in plain English.

AI generating a multi-stage aggregation pipeline

Aggregation Examples

Natural Language Generated Pipeline
"Total sales by category" $group by category, $sum sales
"Top 10 customers by order count" $group by customer, $count, $sort desc, $limit 10
"Average order value per month" $group by month, $avg orderValue
"Join orders with customer details" $lookup from customers

Aggregation Features

  • Multi-Stage Pipelines: Generates complete pipelines with multiple stages
  • Stage Optimization: Orders stages for optimal performance (e.g., $match before $group)
  • Accumulator Selection: Chooses appropriate accumulators ($sum, $avg, $max, $min, etc.)
  • $lookup Support: Automatically configures joins between collections
  • Explain Output: Provides explanations for each generated stage

Walkthrough: "Top 5 customers by revenue last quarter"

Given the prompt "Show me the top 5 customers by revenue in the last quarter, including their name from the customers collection", the AI Assistant produces:

db.orders.aggregate([
  { $match: {
      createdAt: { $gte: ISODate("2026-04-01"), $lt: ISODate("2026-07-01") },
      status:    "completed"
  }},
  { $group: {
      _id:     "$customerId",
      revenue: { $sum: "$total" },
      orders:  { $sum: 1 }
  }},
  { $sort:  { revenue: -1 } },
  { $limit: 5 },
  { $lookup: {
      from:         "customers",
      localField:   "_id",
      foreignField: "_id",
      as:           "customer"
  }},
  { $unwind: "$customer" },
  { $project: {
      _id:      0,
      customer: "$customer.name",
      revenue:  1,
      orders:   1
  }}
]);

Each stage arrives with a short natural-language explanation so you can learn (and audit) the pipeline before applying it.

AI Schema Analysis

Get AI-powered insights into your database schema, including field types, data patterns, and optimization recommendations.

AI schema analysis showing field insights and recommendations

Schema Analysis Features

  • Field Type Detection: Identifies field types and shows distribution
  • Pattern Recognition: Detects data patterns (emails, URLs, dates, etc.)
  • Relationship Detection: Finds potential relationships between collections
  • Anomaly Detection: Flags inconsistent field types or unusual values
  • Index Suggestions: Recommends indexes based on schema structure

Schema Insights

Insight Type Description
Field Summary Human-readable summary of each field's purpose and content
Data Quality Percentage of documents with null/missing fields
Relationships Detected foreign key relationships to other collections
Optimization Tips Suggestions for improving schema design

Conversational Context

The AI Assistant maintains conversation context, allowing you to refine queries through follow-up requests.

Conversation Examples

  • User: "Find all orders from last month"
  • AI: Generates query with date filter
  • User: "Only show orders over $50"
  • AI: Adds total > 50 condition to existing query
  • User: "Sort by date descending"
  • AI: Adds sort stage

Using Generated Code

Apply AI-generated queries directly to VisuaLeaf's query tools.

Apply Options

  • Use in Query Builder: Opens the Visual Query Builder with the generated query pre-loaded
  • Use in Aggregation: Opens the Aggregation Pipeline Builder with generated stages
  • Copy to Shell: Copies the MongoDB shell command to clipboard
  • Execute Directly: Run the query immediately and view results
  • Save Query: Save to your query library for future use

AI Settings

Configure the active provider, model, and how much context the AI Assistant is allowed to see.

AI Settings panel showing configuration options for AI Assistant
Setting Description Default
Provider Which AI backend to use: OpenAI, Anthropic, Google Vertex AI, or Ollama OpenAI
Model Specific model within the selected provider (e.g., claude-sonnet-4, gpt-4o, llama3) Provider-recommended
API Key / Endpoint Your provider credentials (or the Ollama base URL for local inference) Empty
Schema Context Include collection schema in AI requests for better accuracy Enabled
Sample Documents Number of sample documents to include for context (per connection) 5
Explain Output Include explanations with generated code Enabled
Auto-Execute Automatically run generated queries (with confirmation) Disabled

Privacy & Security

The AI Assistant is designed so you decide, per connection, exactly what leaves your machine.

  • Per-connection controls: On every saved connection you can toggle whether the AI is allowed to see the collection schema, sample documents, both, or neither.
  • Schema-only mode (default): Only field names and inferred types are shared — never actual document values.
  • Sample opt-in: When enabled, a small, configurable number of documents (default 5) is shared to improve accuracy. Turn this off for regulated collections.
  • Fully local with Ollama: Select Ollama as the provider and prompts, schema, and completions all stay on your local network — ideal for air-gapped, HIPAA, or SOC 2 environments.
  • Bring-your-own key: API keys are stored on your machine only. VisuaLeaf servers never see keys, prompts, or completions — requests go directly from the app to the provider.
  • No conversation storage: AI chat history is kept locally and never transmitted to VisuaLeaf's backend.
  • Local execution: Generated queries are always executed against your MongoDB from your machine — results never round-trip through any AI provider.

Air-gapped setup (Ollama)

  1. Install Ollama on the same machine or on an internal server.
  2. Pull a model, e.g. ollama pull llama3 or ollama pull mistral.
  3. In VisuaLeaf, open Settings → AI Assistant, choose Ollama, and point it at your endpoint (default http://localhost:11434).
  4. Pick the model you pulled and save. No outbound internet traffic is required for AI features.

Pro Tips

  1. Be Specific: Include field names when you know them for more accurate results.
  2. Use Examples: "Like this: {status: 'active'}" helps AI understand your intent.
  3. Iterate: Start simple and refine through conversation.
  4. Review Output: Always review generated queries before executing on production data.
  5. Learn Syntax: Use AI-generated queries as a learning tool for MongoDB syntax.

Ready to try VisuaLeaf?

Download and start managing your MongoDB databases with ease.

Download Free Trial