MongoDB Atlas provides a free Data API that lets you query, insert, update, and delete documents via simple HTTPS calls — no driver installation, no connection strings, no firewall rules. Perfect for serverless functions, mobile apps, and automation scripts.
Why Use the MongoDB Data API?
- No drivers needed — plain HTTP from any language or tool
- No connection management — each request is stateless
- Built-in auth — API keys instead of database credentials
- Free tier — 512 MB storage, shared cluster, Data API included
Getting Started
Enable Data API in Atlas: App Services > Data API > Enable:
export MONGODB_API_KEY="your-api-key"
export MONGODB_URL="https://data.mongodb-api.com/app/data-xxxxx/endpoint/data/v1"
# Find documents
curl -s -X POST "$MONGODB_URL/action/find" \
-H "api-key: $MONGODB_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"dataSource": "Cluster0",
"database": "mydb",
"collection": "users",
"filter": {"status": "active"},
"limit": 10
}' | jq '.documents[] | {name: .name, email: .email}'
Python Client
import requests
class MongoAPI:
def __init__(self, api_key, app_id, cluster="Cluster0"):
self.url = f"https://data.mongodb-api.com/app/{app_id}/endpoint/data/v1"
self.headers = {"api-key": api_key, "Content-Type": "application/json"}
self.cluster = cluster
def _request(self, action, database, collection, **kwargs):
payload = {"dataSource": self.cluster, "database": database, "collection": collection}
payload.update(kwargs)
resp = requests.post(f"{self.url}/action/{action}", json=payload, headers=self.headers)
return resp.json()
def find(self, db, col, filter={}, limit=100):
return self._request("find", db, col, filter=filter, limit=limit)
def find_one(self, db, col, filter={}):
return self._request("findOne", db, col, filter=filter)
def insert_one(self, db, col, document):
return self._request("insertOne", db, col, document=document)
def insert_many(self, db, col, documents):
return self._request("insertMany", db, col, documents=documents)
def update_one(self, db, col, filter, update):
return self._request("updateOne", db, col, filter=filter, update=update)
def delete_one(self, db, col, filter):
return self._request("deleteOne", db, col, filter=filter)
# Usage
mongo = MongoAPI("your-api-key", "data-xxxxx")
# Insert
mongo.insert_one("mydb", "products", {
"name": "Widget Pro",
"price": 29.99,
"category": "tools",
"in_stock": True
})
# Query
result = mongo.find("mydb", "products", filter={"category": "tools"}, limit=10)
for doc in result["documents"]:
print(f"{doc['name']}: ${doc['price']}")
Aggregation Pipeline
def run_aggregation(mongo, db, collection, pipeline):
payload = {
"dataSource": mongo.cluster,
"database": db,
"collection": collection,
"pipeline": pipeline
}
resp = requests.post(f"{mongo.url}/action/aggregate", json=payload, headers=mongo.headers)
return resp.json()
# Revenue by category
pipeline = [
{"$match": {"status": "completed"}},
{"$group": {
"_id": "$category",
"total_revenue": {"$sum": "$total"},
"order_count": {"$sum": 1},
"avg_order": {"$avg": "$total"}
}},
{"$sort": {"total_revenue": -1}}
]
result = run_aggregation(mongo, "ecommerce", "orders", pipeline)
for doc in result["documents"]:
print(f"{doc['_id']:20s} ${doc['total_revenue']:>10,.2f} ({doc['order_count']} orders)")
Serverless Function Integration
// Cloudflare Worker / Vercel Edge Function
export default async function handler(request) {
const { searchParams } = new URL(request.url);
const category = searchParams.get('category') || 'all';
const filter = category !== 'all' ? { category } : {};
const response = await fetch('https://data.mongodb-api.com/app/data-xxxxx/endpoint/data/v1/action/find', {
method: 'POST',
headers: {
'api-key': process.env.MONGODB_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
dataSource: 'Cluster0',
database: 'mydb',
collection: 'products',
filter: filter,
limit: 50
})
});
const data = await response.json();
return new Response(JSON.stringify(data.documents), {
headers: { 'Content-Type': 'application/json' }
});
}
Real-World Use Case
A startup used MongoDB Atlas Data API to build a serverless product catalog. No backend server needed — their Vercel edge functions queried MongoDB directly. Cold start time dropped from 3 seconds (with MongoDB driver) to 200ms (with Data API). Monthly server costs went from $150 to $0.
What You Can Build
- Serverless API without maintaining a backend
- Mobile app backend with direct database access
- Data pipeline importing/exporting documents via HTTP
- Admin dashboard with CRUD operations via API
- Webhook handler storing events directly in MongoDB
Need custom database solutions? I build data pipelines and automation tools.
Email me: spinov001@gmail.com
Check out my developer tools: https://apify.com/spinov001
Top comments (0)