# MongoDB Database Extractor (`parseforge/mongodb-database-extractor`) Actor

Connects to a MongoDB database and extracts documents from selected collections into a flat dataset. Supports connection strings, SSL, authentication, and per-collection document limits.

- **URL**: https://apify.com/parseforge/mongodb-database-extractor.md
- **Developed by:** [ParseForge](https://apify.com/parseforge) (community)
- **Categories:** Automation, Developer tools, Other
- **Stats:** 2 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: 5.00 out of 5 stars

## Pricing

Pay per event

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

[![ParseForge](https://raw.githubusercontent.com/ParseForge/apify-assets/main/banner.jpg)](https://apify.com/parseforge?fpr=vmoqkp)

### MongoDB Database Extractor

**Extract documents from any MongoDB database, local or Atlas, into structured datasets.** Connect with a standard URI or host and credentials, pick collections, and export every document as a flat JSON row to CSV, JSON, Excel, or XML.

Moving MongoDB data into analytics tools or spreadsheets usually means writing custom scripts, handling connection pooling, and dealing with BSON type conversions. This Actor connects to your MongoDB instance, reads the documents you specify, and delivers them in a clean, tabular format ready for downstream processing. No custom code, no drivers to install.

| Who uses it | What they scrape MongoDB for |
|---|---|
| Data analysts | Pull production data into a CSV for ad-hoc analysis in Excel or Pandas. |
| Backend developers | Create regular backups of specific collections to cloud storage. |
| Data engineers | Feed MongoDB collections into an ETL pipeline or data warehouse. |
| QA engineers | Export test data snapshots to validate application behavior. |

### What it does

This Actor connects to a MongoDB database, extracts documents from selected collections, and returns each document as a flat JSON row.

- 🗂️ **Selective collection extraction:** specify exactly which collections to pull, or exclude noisy ones like logs and temp data.
- 🔐 **Full authentication support:** username, password, and a separate authentication database for secure deployments.
- 🔒 **SSL encryption:** toggle SSL on for Atlas and other cloud-hosted MongoDB instances.
- 📏 **Document capping:** set a maximum number of documents per collection to sample large datasets without a full dump.

Results export to CSV, JSON, Excel, or XML, or straight from the API.

### What you can do with MongoDB data

**📊 Feed a BI dashboard.**

A data analyst runs the Actor weekly on the 'orders' and 'customers' collections to refresh a Tableau extract with the latest sales data.

**🗄️ Archive old collections.**

A DevOps engineer excludes the active 'sessions' collection and dumps historical 'audit\_logs' to JSON files stored in S3 for compliance.

**🧪 Seed a staging environment.**

A developer caps the 'users' collection at 500 documents to create a sanitized, lightweight dataset for local testing.

**🔍 Investigate a data issue.**

A support engineer extracts the single 'error\_events' collection from the production database to search for patterns in a recent outage.

### Why choose this scraper

| | What you get |
|---|---|
| **No driver setup** | Connect with a standard MongoDB URI or host fields, no npm install required. |
| **Handles BSON types** | Dates, ObjectIDs, and binary data are serialized to JSON-safe strings automatically. |
| **Cloud ready** | Works with MongoDB Atlas, self-hosted clusters, and Docker instances with SSL support. |
| **Flat row output** | Every document becomes one row in a CSV, JSON, Excel, or XML dataset, no nested wrangling. |

### How it compares

No other Store actor targets MongoDB the same way, so the honest comparison is with the alternatives teams actually weigh.

| | MongoDB Database Extractor | Build it in-house | By hand |
|---|---|---|---|
| Setup | Run it now, zero config | Days of engineering | None, but hours per pull |
| When MongoDB changes | Maintained for you | You fix it | You re-learn the page |
| Proxies, retries, anti-bot | Built in | Your problem | Browser only |
| Output | Fixed JSON schema, CSV/Excel export | Whatever you build | Copy-paste |
| Cost | Pay per result | Engineering time | Analyst hours |

### Configure the run

Provide a connection string or individual host, port, and credentials, then narrow the extraction by including or excluding specific collections and setting a per-collection document limit. The Input tab lists every parameter.

A first run with the defaults:

```json
{
 "host": "51.222.13.168",
 "port": 27017,
 "database": "myappdb",
 "username": "admin",
 "password": "securepassword123",
 "authSource": "admin",
 "ssl": false,
 "collections": [],
 "excludeCollections": [],
 "maxDocumentsPerCollection": 100
}
```

### Pricing

Pay-per-result: **$0.016 per result** collected. You pay only for the results written to your dataset.

| Results collected | Approximate cost |
|---|---|
| 100 results | $1.60 |
| 1,000 results | $16.00 |
| 10,000 results | $160.00 |

New Apify accounts start with $5 in free credit.

### Free users

Free-plan runs return up to 10 results as a preview. [Upgrade your Apify plan](https://console.apify.com/sign-up?fpr=vmoqkp) to collect up to 1,000,000 results per run.

### Run it

1. [Create a free Apify account with $5 in credit](https://console.apify.com/sign-up?fpr=vmoqkp).
2. Open the [MongoDB Database Extractor](https://apify.com/parseforge/mongodb-database-extractor?fpr=vmoqkp).
3. Set your inputs and any filters, then click **Start**.
4. Export the results as CSV, Excel, JSON, or XML from the **Dataset** tab.

Run it programmatically through the [Apify API](https://docs.apify.com/api/v2) (`run-sync-get-dataset-items`) or the [ApifyClient](https://docs.apify.com/api/client/js) for JavaScript and Python.

### Use with AI agents (MCP)

Give an AI agent live access to MongoDB through the Model Context Protocol. Add the Actor to Claude, Cursor, or any MCP client:

```bash
claude mcp add --transport http apify "https://mcp.apify.com/?tools=parseforge/mongodb-database-extractor"
```

Then prompt it in plain language to run the scraper and read back the results.

### Troubleshooting

**The run fails with an authentication error.**

Check that the username, password, and authentication database fields are correct. If your user is defined in the 'admin' database, make sure 'Authentication Database' is set to 'admin'.

**I get a connection timeout.**

Verify that your MongoDB host is reachable from the internet. If it is behind a firewall, you will need to whitelist Apify's IP addresses or use a tunnel.

**The dataset is empty even though the run succeeded.**

Confirm the collection names in 'Collections to Extract' match exactly, including case. Also check that the collections are not listed in 'Collections to Exclude'.

**SSL connection fails.**

Ensure the 'Use SSL' checkbox is enabled. If your server uses a self-signed certificate, you may need to use a connection string with the tlsAllowInvalidCertificates parameter.

**The output contains \[Object] instead of real data.**

Complex BSON types or deeply nested objects are serialized to JSON strings. If you see an unexpected string, the original field contained a sub-document or array that was flattened.

### FAQ

| Question | Answer |
|---|---|
| Can this connect to MongoDB Atlas? | Yes. Use the connection string field with your mongodb+srv URI and enable the SSL toggle. The Actor will connect to your Atlas cluster securely. |
| What happens to nested documents and arrays? | Nested objects and arrays are stringified into a JSON string within the parent document's row. This keeps the output flat and compatible with CSV and spreadsheet formats. |
| How do I extract only a few collections, not the whole database? | List the collection names in the 'Collections to Extract' field. The Actor will read only those and skip everything else. |
| Is my connection string stored securely? | Yes. All input fields, including the connection string and password, are encrypted at rest and only used during the run to establish the database connection. |
| Can I limit the number of documents pulled? | Yes. Set the 'Max Documents Per Collection' field to a number like 1000, and the Actor will stop reading each collection after reaching that limit. |
| Does this work with a replica set? | Yes. If your connection string includes a replica set name or multiple hosts, the Actor will use the standard MongoDB driver to connect to the replica set. |
| What output formats are supported? | You can export the extracted documents to CSV, JSON, Excel, or XML directly from the Apify dataset tab after the run finishes. |
| Can I run this on a schedule? | Yes. Apify's scheduler lets you run the Actor every hour, day, or week to keep your extracted data up to date automatically. |
| What if my database requires a different authentication source? | Use the 'Authentication Database' field. Set it to 'admin' or the name of the database where your user credentials are stored. |
| Does this Actor modify or delete any data? | No. It performs read-only find queries. It will never insert, update, or delete documents in your database. |

### Related actors

Browse the full [ParseForge collection](https://apify.com/parseforge?fpr=vmoqkp) for more scrapers.

🆘 **Need help?** Email parseforge@protonmail.com with your run ID, your input, and what you expected.

⚠️ **Disclaimer.** This Actor is unofficial and is not affiliated with, endorsed by, or sponsored by MongoDB, Inc. It collects only publicly available data. You are responsible for using the collected data in compliance with the source's terms of service and applicable data-protection laws, including GDPR, CCPA, and PIPL. Do not use it to collect personal data unlawfully.

# Actor input Schema

## `connectionString` (type: `string`):

MongoDB connection string (e.g., mongodb://user:password@host:port/database or mongodb+srv:// for Atlas). If provided, other connection parameters will be ignored. The prefill points to MongoDB's public read-only COVID-19 sample cluster so you can try the actor instantly.

## `host` (type: `string`):

MongoDB server hostname or IP address

## `port` (type: `integer`):

MongoDB server port (default: 27017)

## `database` (type: `string`):

Database name to connect to

## `username` (type: `string`):

MongoDB username (required if authentication is enabled)

## `password` (type: `string`):

MongoDB password (required if authentication is enabled)

## `authSource` (type: `string`):

Database name to use for authentication (e.g., 'admin'). Required if user is stored in a different database than the target database.

## `ssl` (type: `boolean`):

Enable SSL connection (required for most cloud databases)

## `collections` (type: `array`):

List of specific collections to extract (e.g., \['users', 'orders']). If not provided, all collections will be extracted.

## `excludeCollections` (type: `array`):

List of collections to exclude from extraction (e.g., \['logs', 'temp\_data'])

## `maxDocumentsPerCollection` (type: `integer`):

Maximum number of documents to extract from each collection. If not specified, all documents will be extracted.

## Actor input object example

```json
{
  "connectionString": "mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/covid19",
  "port": 27017,
  "database": "covid19",
  "authSource": "admin",
  "collections": [
    "metadata"
  ],
  "excludeCollections": [],
  "maxDocumentsPerCollection": 100
}
```

# Actor output Schema

## `overview` (type: `string`):

Overview view of collections with key fields displayed in a table format

## `collections` (type: `string`):

Complete collection dataset with all fields including collection name, document information, and extraction metadata

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "connectionString": "mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/covid19",
    "port": 27017,
    "database": "covid19",
    "authSource": "admin",
    "ssl": false,
    "collections": [
        "metadata"
    ],
    "excludeCollections": [],
    "maxDocumentsPerCollection": 100
};

// Run the Actor and wait for it to finish
const run = await client.actor("parseforge/mongodb-database-extractor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "connectionString": "mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/covid19",
    "port": 27017,
    "database": "covid19",
    "authSource": "admin",
    "ssl": False,
    "collections": ["metadata"],
    "excludeCollections": [],
    "maxDocumentsPerCollection": 100,
}

# Run the Actor and wait for it to finish
run = client.actor("parseforge/mongodb-database-extractor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "connectionString": "mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/covid19",
  "port": 27017,
  "database": "covid19",
  "authSource": "admin",
  "ssl": false,
  "collections": [
    "metadata"
  ],
  "excludeCollections": [],
  "maxDocumentsPerCollection": 100
}' |
apify call parseforge/mongodb-database-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,parseforge/mongodb-database-extractor"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/eG5D2AzLQgqfqmRZY/builds/Fp1untCkpSzjpebK6/openapi.json
