MongoDB Atlas Data API

Access your data via HTTPS endpoints

🌐 What is Atlas Data API?

The Atlas Data API provides HTTPS endpoints to read and write data without database drivers. Perfect for serverless apps, mobile clients, and web applications needing simple database access.


// Access MongoDB via HTTPS
fetch('https://data.mongodb-api.com/app/data-xxxxx/endpoint/data/v1/action/findOne', {
  method: 'POST',
  headers: { 'api-key': 'your-api-key' },
  body: JSON.stringify({ collection: 'users', database: 'mydb', filter: { name: 'John' } })
})
                                    

Output:

{ "document": { "_id": "...", "name": "John", "email": "[email protected]" } }

Key API Features

🔌

No Drivers Needed

Use standard HTTPS requests

// Just fetch API
fetch(endpoint, options)
🔑

API Key Auth

Simple authentication method

headers: {
  'api-key': 'your-key'
}

Serverless Ready

Perfect for edge functions

// Works in Vercel, Netlify
// Cloudflare Workers, etc.
📱

Cross-Platform

Use from any language

// JavaScript, Python
// Swift, Kotlin, etc.

🔹 Enabling Data API

Enable the Data API in your Atlas cluster settings and generate API keys for authentication.

Setup Steps:

  1. Go to your Atlas cluster
  2. Click "Data API" in left sidebar
  3. Enable the Data API
  4. Create an API key
  5. Copy your endpoint URL
  6. Set up CORS if needed
// Your Data API endpoint
const BASE_URL = "https://data.mongodb-api.com/app/data-xxxxx/endpoint/data/v1";
const API_KEY = "your-api-key-here";

🔹 Finding Documents

Use findOne and find endpoints to query documents from your collections via HTTPS requests.

// Find one document
async function findOneUser(email) {
  const response = await fetch(`${BASE_URL}/action/findOne`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'api-key': API_KEY
    },
    body: JSON.stringify({
      dataSource: 'Cluster0',
      database: 'myapp',
      collection: 'users',
      filter: { email: email }
    })
  });
  
  const data = await response.json();
  return data.document;
}

// Find multiple documents
async function findUsers(filter = {}) {
  const response = await fetch(`${BASE_URL}/action/find`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'api-key': API_KEY
    },
    body: JSON.stringify({
      dataSource: 'Cluster0',
      database: 'myapp',
      collection: 'users',
      filter: filter,
      limit: 10
    })
  });
  
  const data = await response.json();
  return data.documents;
}

Output:

{ "_id": "...", "name": "John", "email": "[email protected]", "age": 30 }

🔹 Inserting Documents

Add new documents to your collections using insertOne and insertMany endpoints.

// Insert one document
async function createUser(userData) {
  const response = await fetch(`${BASE_URL}/action/insertOne`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'api-key': API_KEY
    },
    body: JSON.stringify({
      dataSource: 'Cluster0',
      database: 'myapp',
      collection: 'users',
      document: userData
    })
  });
  
  const data = await response.json();
  return data.insertedId;
}

// Insert multiple documents
async function createMultipleUsers(usersArray) {
  const response = await fetch(`${BASE_URL}/action/insertMany`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'api-key': API_KEY
    },
    body: JSON.stringify({
      dataSource: 'Cluster0',
      database: 'myapp',
      collection: 'users',
      documents: usersArray
    })
  });
  
  const data = await response.json();
  return data.insertedIds;
}

// Usage
await createUser({ name: 'Alice', email: '[email protected]', age: 25 });

Output:

{ "insertedId": "65a1b2c3d4e5f6789012345" }

🔹 Updating Documents

Modify existing documents using updateOne and updateMany endpoints with MongoDB update operators.

// Update one document
async function updateUser(userId, updates) {
  const response = await fetch(`${BASE_URL}/action/updateOne`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'api-key': API_KEY
    },
    body: JSON.stringify({
      dataSource: 'Cluster0',
      database: 'myapp',
      collection: 'users',
      filter: { _id: { $oid: userId } },
      update: { $set: updates }
    })
  });
  
  const data = await response.json();
  return data.modifiedCount;
}

// Update multiple documents
async function updateManyUsers(filter, updates) {
  const response = await fetch(`${BASE_URL}/action/updateMany`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'api-key': API_KEY
    },
    body: JSON.stringify({
      dataSource: 'Cluster0',
      database: 'myapp',
      collection: 'users',
      filter: filter,
      update: { $set: updates }
    })
  });
  
  const data = await response.json();
  return data.modifiedCount;
}

// Usage
await updateUser('65a1b2c3d4e5f6789012345', { age: 31, city: 'New York' });

🔹 Deleting Documents

Remove documents from collections using deleteOne and deleteMany endpoints.

// Delete one document
async function deleteUser(userId) {
  const response = await fetch(`${BASE_URL}/action/deleteOne`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'api-key': API_KEY
    },
    body: JSON.stringify({
      dataSource: 'Cluster0',
      database: 'myapp',
      collection: 'users',
      filter: { _id: { $oid: userId } }
    })
  });
  
  const data = await response.json();
  return data.deletedCount;
}

// Delete multiple documents
async function deleteInactiveUsers() {
  const response = await fetch(`${BASE_URL}/action/deleteMany`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'api-key': API_KEY
    },
    body: JSON.stringify({
      dataSource: 'Cluster0',
      database: 'myapp',
      collection: 'users',
      filter: { lastLogin: { $lt: '2023-01-01' } }
    })
  });
  
  const data = await response.json();
  return data.deletedCount;
}

Output:

{ "deletedCount": 1 }

🔹 Aggregation Pipeline

Run complex aggregation queries using the aggregate endpoint for data analysis and transformation.

// Run aggregation pipeline
async function getUserStats() {
  const response = await fetch(`${BASE_URL}/action/aggregate`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'api-key': API_KEY
    },
    body: JSON.stringify({
      dataSource: 'Cluster0',
      database: 'myapp',
      collection: 'users',
      pipeline: [
        { $group: { _id: '$city', count: { $sum: 1 }, avgAge: { $avg: '$age' } } },
        { $sort: { count: -1 } },
        { $limit: 5 }
      ]
    })
  });
  
  const data = await response.json();
  return data.documents;
}

// Usage
const stats = await getUserStats();
console.log(stats);

Output:

[
  { "_id": "New York", "count": 150, "avgAge": 32.5 },
  { "_id": "Los Angeles", "count": 120, "avgAge": 29.8 }
]

🧠 Test Your Knowledge

What protocol does the Atlas Data API use?