TL;DR
MongoDB Charts offers two embedding paths: iframe (quick but limited) and JavaScript SDK (more control with auth and filtering). Iframe works for prototypes; the SDK handles authenticated, filtered dashboards. But neither provides true multi-tenancy, row-level security, cross-collection joins, or full white-labeling which is where purpose-built embedded analytics platforms take over for customer-facing SaaS.
This tutorial covers embedding MongoDB Charts dashboards into your web application, providing interactive data visualizations for your users.
Table of Contents
- Prerequisites
- Overview
- Part 1: Creating a Chart in MongoDB Charts
- Part 2: Embedding with Iframe (Simple Method)
- Part 3: Embedding with JavaScript SDK (Recommended)
- Part 4: Authenticated Embedding
- Part 5: Dynamic Filtering
- Part 6: Embedding Full Dashboards
- Part 7: Event Handling
- Best Practices
- Troubleshooting
- When MongoDB Charts Is the Right Fit
- What MongoDB Charts Embedding Supports
- Creating Charts in MongoDB Charts (Baseline Setup)
- Embedding via Iframe (What Most Teams Start With)
- Embedding with the JavaScript SDK (Where Complexity Starts)
- Authentication Options (What’s Actually Possible)
- Dynamic Filtering (Useful, but Not Security)
- Embedding Full Dashboards
- Known Limitations Teams Hit
- Summary: Where MongoDB Charts Fits
- Frequently Asked Questions
- Can MongoDB Charts handle multi-tenant embedded analytics?
- Is MongoDB Charts free to use?
- What’s the difference between iframe embedding and SDK embedding in MongoDB Charts?
- Can I join MongoDB data with other databases in MongoDB Charts?
- When should I move beyond MongoDB Charts for embedded analytics?
- Does MongoDB Charts work outside of MongoDB Atlas?
- How do I make MongoDB Charts dashboards look like part of my app?
- Related Resources
Prerequisites
- MongoDB Atlas account with an active cluster
- MongoDB Charts enabled on your Atlas project
- A web application (React, Vue, Angular, or vanilla JavaScript)
- Basic knowledge of JavaScript and HTML
Overview
MongoDB Charts is Atlas’s built-in visualization tool that allows you to create dashboards directly from your MongoDB data. For a comparison of MongoDB Charts against other visualization options, see MongoDB Charts: What It Is, How It Works, And What It’s Used For and The Best MongoDB Visualization, Reporting and Analytics Tools. You can embed these charts in your applications using:
- Iframe Embedding – Simple HTML iframe integration
- JavaScript SDK – Programmatic control with the Charts Embedding SDK
Part 1: Creating a Chart in MongoDB Charts
Step 1: Access MongoDB Charts
- Log into MongoDB Atlas
- Navigate to your project
- Click Charts in the left sidebar
- Click Add Dashboard to create a new dashboard
Step 2: Create Your First Chart
- Click Add Chart on your dashboard
- Select your data source (database and collection)
- Choose a chart type (bar, line, pie, etc.)
- Drag fields to configure your visualization
- Click Save and Close
Part 2: Embedding with Iframe (Simple Method)
Step 1: Enable Embedding for Your Chart
- Open your chart in MongoDB Charts
- Click the … menu on the chart
- Select Embed Chart
- Toggle Enable unauthenticated access (for public charts) or configure authentication
- Copy the iframe embed code
Step 2: Add to Your HTML
<!DOCTYPE html>
<html>
<head>
<title>MongoDB Dashboard</title>
<style>
.chart-container {
width: 100%;
max-width: 800px;
margin: 0 auto;
}
iframe {
width: 100%;
height: 480px;
border: none;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<div class="chart-container">
<iframe
src="https://charts.mongodb.com/charts-project-xxxxx/embed/charts?id=xxxxx-xxxxx-xxxxx&maxDataAge=3600&theme=light&autoRefresh=true"
allowfullscreen>
</iframe>
</div>
</body>
</html>
Iframe URL Parameters
| Parameter | Description |
|---|---|
| maxDataAge | Cache duration in seconds |
| theme | light or dark |
| autoRefresh | Enable automatic data refresh |
| filter | JSON filter to apply to the chart |
Part 3: Embedding with JavaScript SDK (Recommended)
The SDK provides more control, including programmatic filtering and authenticated embedding.
Step 1: Install the SDK
npm install @mongodb-js/charts-embed-dom
Or include via CDN:
<script src="https://unpkg.com/@mongodb-js/charts-embed-dom"></script>
Step 2: Get Your Embed Credentials
- In MongoDB Charts, click … on your chart
- Select Embed Chart
- Choose Verified Signature or Authenticated embedding
- Copy your Base URL and Chart ID
Step 3: Basic SDK Implementation
import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
// Initialize the SDK
const sdk = new ChartsEmbedSDK({
baseUrl: 'https://charts.mongodb.com/charts-project-xxxxx'
});
// Create the chart
const chart = sdk.createChart({
chartId: 'xxxxx-xxxxx-xxxxx',
height: '400px',
width: '600px',
theme: 'light',
autoRefresh: true,
maxDataAge: 300 // 5 minutes
});
// Render the chart
chart.render(document.getElementById('chart-container'));
Step 4: React Implementation
import React, { useEffect, useRef } from 'react';
import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
const MongoDBChart = ({ chartId, filter }) => {
const chartRef = useRef(null);
const renderedChart = useRef(null);
useEffect(() => {
const sdk = new ChartsEmbedSDK({
baseUrl: 'https://charts.mongodb.com/charts-project-xxxxx'
});
const chart = sdk.createChart({
chartId: chartId,
height: '400px',
theme: 'light'
});
chart.render(chartRef.current).then(() => {
renderedChart.current = chart;
});
return () => {
// Cleanup on unmount
if (renderedChart.current) {
renderedChart.current = null;
}
};
}, [chartId]);
// Update filter when it changes
useEffect(() => {
if (renderedChart.current && filter) {
renderedChart.current.setFilter(filter);
}
}, [filter]);
return <div ref={chartRef} className="chart-container" />;
};
// Usage
function App() {
const [dateFilter, setDateFilter] = useState({
createdAt: { $gte: new Date('2024-01-01') }
});
return (
<div>
<h1>Sales Dashboard</h1>
<MongoDBChart
chartId="xxxxx-xxxxx-xxxxx"
filter={dateFilter}
/>
</div>
);
}
export default App;
Part 4: Authenticated Embedding
For secure, user-specific dashboards, use authenticated embedding.
Option A: Realm App Services Authentication
import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
import * as Realm from 'realm-web';
const app = new Realm.App({ id: 'your-app-id' });
async function renderAuthenticatedChart() {
// Login user
const credentials = Realm.Credentials.emailPassword(
'user@example.com',
'password'
);
const user = await app.logIn(credentials);
// Initialize SDK with user token
const sdk = new ChartsEmbedSDK({
baseUrl: 'https://charts.mongodb.com/charts-project-xxxxx',
getUserToken: () => user.accessToken
});
const chart = sdk.createChart({
chartId: 'xxxxx-xxxxx-xxxxx'
});
await chart.render(document.getElementById('chart'));
}
Option B: Custom JWT Authentication
const sdk = new ChartsEmbedSDK({
baseUrl: 'https://charts.mongodb.com/charts-project-xxxxx',
getUserToken: async () => {
// Fetch JWT from your backend
const response = await fetch('/api/charts-token');
const { token } = await response.json();
return token;
}
});
Part 5: Dynamic Filtering
Apply filters programmatically to show user-specific data.
const chart = sdk.createChart({
chartId: 'xxxxx-xxxxx-xxxxx',
filter: {
// Initial filter
region: 'North America'
}
});
await chart.render(document.getElementById('chart'));
// Update filter dynamically
document.getElementById('region-select').addEventListener('change', (e) => {
chart.setFilter({ region: e.target.value });
});
// Combine multiple filters
chart.setFilter({
region: 'Europe',
status: 'active',
revenue: { $gte: 10000 }
});
// Clear filters
chart.setFilter({});
Part 6: Embedding Full Dashboards
Embed an entire dashboard instead of individual charts.
const sdk = new ChartsEmbedSDK({
baseUrl: 'https://charts.mongodb.com/charts-project-xxxxx'
});
const dashboard = sdk.createDashboard({
dashboardId: 'xxxxx-xxxxx-xxxxx',
height: '800px',
widthMode: 'scale', // 'scale' or 'fixed'
heightMode: 'fixed',
theme: 'dark',
showAttribution: false
});
dashboard.render(document.getElementById('dashboard-container'));
// Apply filter to all charts in dashboard
dashboard.setFilter({ organizationId: 'org-123' });
// Refresh all charts
dashboard.refresh();
Part 7: Event Handling
Listen to chart events for interactivity.
const chart = sdk.createChart({
chartId: 'xxxxx-xxxxx-xxxxx'
});
// Listen for click events
chart.addEventListener('click', (payload) => {
console.log('Clicked data point:', payload.data);
// Navigate to detail view, show modal, etc.
});
// Listen for refresh events
chart.addEventListener('refreshstart', () => {
console.log('Chart is refreshing...');
});
chart.addEventListener('refreshend', () => {
console.log('Chart refresh complete');
});
// Get current chart data
const data = await chart.getData();
console.log('Chart data:', data);
Best Practices
Performance
- Set appropriate maxDataAge – Balance freshness vs. performance
- Use filters – Reduce data transferred to the client
- Lazy load charts – Only render charts when visible
// Intersection Observer for lazy loading
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
renderChart(entry.target);
observer.unobserve(entry.target);
}
});
});
document.querySelectorAll('.chart-placeholder').forEach(el => {
observer.observe(el);
});
Security
- Use authenticated embedding for sensitive data
- Apply server-side filters via JWT claims
- Never expose embedding credentials in client-side code
- Enable CORS only for your domains in Atlas settings
Responsive Design
.chart-container {
width: 100%;
min-height: 300px;
max-height: 600px;
}
@media (max-width: 768px) {
.chart-container {
height: 250px;
}
}
Troubleshooting
| Issue | Solution |
|---|---|
| Chart not rendering | Check if embedding is enabled and URL/ID are correct |
| CORS errors | Add your domain to allowed origins in Charts settings |
| Authentication failed | Verify JWT token format and expiration |
| Filters not applying | Ensure field names match your collection schema |
| Slow loading | Increase maxDataAge, add database indexes |
Start with iframe embedding for quick prototypes, then migrate to the SDK when you need programmatic control or authentication. If you need multi-tenant security, cross-source joins, or full white-labeling, see The Complete Guide to Embedded Analytics with Knowi.
When MongoDB Charts Is the Right Fit
MongoDB Charts embedding works well if:
- Your dashboards are **internal or lightly shared**
- Data is **non-sensitive or aggregate**
- You don’t need strict tenant isolation
- You’re embedding a **small number of charts**
- You’re optimizing for **speed to first dashboard**
Most teams start here.
What MongoDB Charts Embedding Supports
MongoDB Charts lets you embed visualizations using two approaches:
1. Iframe Embedding (Fastest Path)
- Simple <iframe> embed
- Optional public or authenticated access
- Minimal setup
- Best for prototypes and internal tools
2. Charts Embedding SDK (More Control)
- Programmatic rendering
- Dynamic filters
- Authenticated embedding
- Better lifecycle control
The SDK is typically used once analytics moves inside the product, not just alongside it.
Creating Charts in MongoDB Charts (Baseline Setup)
To embed anything, you first need charts.
Steps
- Log into MongoDB Atlas
- Open Charts from the left sidebar
- Create a dashboard
- Add charts from a single collection
- Save the dashboard
At this stage, MongoDB Charts works like a traditional BI layer on top of MongoDB.
Embedding via Iframe (What Most Teams Start With)
Iframe embedding is the simplest way to get charts into your app.
How it works
- MongoDB hosts the visualization
- Your app renders it via iframe
- Optional URL parameters control refresh, theme, and filters
Where iframe embedding starts to strain
- Filters are client-side and modifiable
- No tenant-level enforcement
- Limited customization
- Not suitable for sensitive customer data
Iframe works well until analytics becomes customer-facing.
Embedding with the JavaScript SDK (Where Complexity Starts)
Once you need authentication, dynamic filtering, or tighter integration, teams move to the SDK.
What the SDK adds
- Authenticated embedding
- Programmatic filters
- Dashboard lifecycle control
- Better UX control than iframe
What it still doesn’t solve
- True row-level security
- Multi-tenant enforcement
- Cross-collection analytics
- Deep event-level interactivity
This is usually the inflection point where teams reassess whether MongoDB Charts can scale with the product.
Authentication Options (What’s Actually Possible)
MongoDB Charts supports authenticated embedding using:
Option 1: Atlas App Services (formerly Realm)
- Users authenticate via MongoDB’s auth layer
- Charts access is tied to user tokens
- Works for internal or MongoDB-centric apps
Option 2: Custom JWT Authentication
- JWT issued by your backend
- Claims can be mapped to chart filters
- Requires careful server-side enforcement
Important: Filters ≠ security. Filters can reduce data shown, but MongoDB Charts does not offer true row-level or tenant isolation for embedded analytics. For a detailed look at security tradeoffs, see SSO vs Secure URL Embedding.
Dynamic Filtering (Useful, but Not Security)
You can apply filters programmatically:
chart.setFilter({ region: 'Europe' });
This works well for:
- UX personalization
- Simple segmentation
- Interactive dashboards
It should not be used to enforce customer isolation in a SaaS product.
Embedding Full Dashboards
You can embed entire dashboards instead of individual charts:
- Faster setup
- Consistent layouts
- Shared filters across charts
This works well for internal teams and single-tenant apps, but becomes harder to manage as customer count grows.
Known Limitations Teams Hit
This is where most evaluations get serious:
- Single-collection analytics only
- No joins across MongoDB collections or external sources (see How to Join MongoDB Data with MySQL, Elasticsearch, REST APIs for what’s possible with federation)
- Limited customization and theming
- No reliable click-level events or data extraction
- Filters are not security boundaries
- Scaling embedded analytics increases operational complexity
For many teams, this is the point where MongoDB Charts stops being “good enough.”
Summary: Where MongoDB Charts Fits
MongoDB Charts is a solid choice when:
- You need dashboards quickly
- Your data is non-sensitive
- Analytics is supportive, not core
Teams typically outgrow it when:
- Analytics becomes a **product feature**
- Customers expect isolation and customization
- Data spans multiple collections or sources
- Engineering becomes the bottleneck again
At that stage, most teams evaluate purpose-built embedded analytics platforms rather than extending Charts further.
Frequently Asked Questions
Can MongoDB Charts handle multi-tenant embedded analytics?
MongoDB Charts supports filtering via the SDK, which lets you pass user-specific parameters to restrict data at render time. However, this is client-side filtering, not true multi-tenancy. There’s no built-in tenant model, no row-level security enforcement, and no audit trail for data isolation. For customer-facing SaaS with strict data separation requirements, you’ll need to build the tenant isolation layer yourself or use a purpose-built platform.
Is MongoDB Charts free to use?
Yes, MongoDB Charts is included with MongoDB Atlas at no additional cost. You can create dashboards and embed them using iframes or the JavaScript SDK. However, advanced features like full white-labeling, cross-collection joins, and production-grade multi-tenancy require additional tooling or a dedicated embedded analytics platform.
What’s the difference between iframe embedding and SDK embedding in MongoDB Charts?
Iframe embedding is the simplest method, you copy an embed URL and place it in an <iframe> tag. It’s fast to set up but offers limited control over authentication, filtering, and styling. The JavaScript SDK provides programmatic control, including authenticated embedding, dynamic filters, and chart lifecycle management. Most teams start with iframe and move to SDK when analytics moves inside the product.
Can I join MongoDB data with other databases in MongoDB Charts?
No. MongoDB Charts only visualizes data from a single MongoDB collection per chart. It doesn’t support cross-collection joins or joins with external databases like PostgreSQL, MySQL, or Elasticsearch. If your analytics require combining data from multiple sources, see How to Join MongoDB Data with MySQL, Elasticsearch, REST APIs.
When should I move beyond MongoDB Charts for embedded analytics?
Teams typically outgrow MongoDB Charts when analytics becomes a core product feature, customers expect data isolation and branded dashboards, data spans multiple collections or external sources, or engineering time spent on embedding workarounds exceeds the cost of a dedicated platform. If you’re evaluating alternatives, see MongoDB Charts vs Metabase vs Knowi.
Does MongoDB Charts work outside of MongoDB Atlas?
No. MongoDB Charts is exclusive to MongoDB Atlas, it cannot connect to self-hosted MongoDB deployments, other databases, or REST APIs. If you need analytics on self-hosted MongoDB or need to combine MongoDB with other data sources, you’ll need an alternative tool.
How do I make MongoDB Charts dashboards look like part of my app?
MongoDB Charts offers basic theming (light/dark mode) and the ability to hide attribution via showAttribution: false in the SDK. However, full white-labeling, custom fonts, colors, logos, and complete branding removal, is limited. For a fully branded experience, see White-Label Embedded Analytics: Complete Guide for SaaS.
Related Resources
- MongoDB Analytics Made Easy with Knowi: A Step-by-Step Guide
- Is MongoDB Good for Analytics?
- Challenges of Traditional MongoDB Analytics
- White-Label Embedded Analytics: Complete Guide for SaaS
- Best Embedded Analytics Tools 2026
- Why Embedded Analytics Fails Without a Data Layer
Learn more about how you can embed MongoDB Charts without any limitations. Request a Demo →