> ## Documentation Index
> Fetch the complete documentation index at: https://docs.notte.cc/llms.txt
> Use this file to discover all available pages before exploring further.

# MongoDB

> Save Notte browser scrapes to MongoDB in Python or TypeScript.

> [!TIP]
>
> Read [the Notte skill](https://notte.cc/skill.md) and follow its setup instructions when setting up Notte or building browser automation. This is the shared source for CLI setup, authentication, and the browser-to-code workflow.

Save browser content to MongoDB with its official drivers. These examples scrape a page through Notte, insert a document, and close both connections.

## Set up

For Python 3.11+, run `pip install notte-sdk pymongo==4.19.0`. For Node.js 24+, run `npm install notte-sdk mongodb@7.7.0` and set `"type": "module"` in `package.json`.

Set `NOTTE_API_KEY` to your [Notte API key](https://console.notte.cc/apikeys) and `MONGODB_URI` to your [MongoDB connection string](https://www.mongodb.com/docs/atlas/driver-connection/). Use a local MongoDB server or an existing Atlas deployment.

## Save a page

Save the example as `notte_mongodb.py` or `notte_mongodb.ts`. Run `python notte_mongodb.py` or `node --experimental-strip-types notte_mongodb.ts`.

```python notte_mongodb.py theme={null}
import os
from typing import Any

from notte_sdk import NotteClient
from pymongo import MongoClient
from pymongo.errors import OperationFailure

url = "https://example.com"
uri = os.environ.get("MONGODB_URI")
if not uri:
    raise ValueError("Set MONGODB_URI before running this example")

with NotteClient().Session(max_duration_minutes=3) as session:
    stage = "MongoDB connection"
    try:
        with MongoClient[dict[str, Any]](uri, timeoutMS=10_000, serverSelectionTimeoutMS=10_000) as mongo:
            mongo.admin.command("ping")
            collection = mongo[os.environ.get("MONGODB_DATABASE", "notte")][
                os.environ.get("MONGODB_COLLECTION", "pages")
            ]
            stage = "browser navigation"
            session.execute(type="goto", url=url)
            stage = "browser scrape"
            markdown = session.scrape()
            stage = "MongoDB insert"
            inserted = collection.insert_one({"url": url, "markdown": markdown, "session_id": session.session_id})
            result = {"document_id": str(inserted.inserted_id), "session_id": session.session_id}
            print(result["document_id"])
    except Exception as error:
        code = error.code if isinstance(error, OperationFailure) else None
        raise RuntimeError(
            f"MongoDB export failed (session {session.session_id}, code {code}): {stage}: {type(error).__name__}"
        ) from None
```

```typescript notte_mongodb.ts theme={null}
import { MongoClient, MongoServerError } from 'mongodb';
import { NotteClient } from 'notte-sdk';

const url = 'https://example.com';
const uri = process.env.MONGODB_URI;
if (!uri) throw new Error('Set MONGODB_URI before running this example');

export const result = await new NotteClient().Session({ max_duration_minutes: 3 }).use(async (session) => {
  let stage = 'MongoDB connection';
  try {
    const mongo = new MongoClient(uri, { timeoutMS: 10_000, serverSelectionTimeoutMS: 10_000 });
    let documentId: string;
    let cleanupFailed = false;
    try {
      await mongo.connect();
      const collection = mongo.db(process.env.MONGODB_DATABASE || 'notte')
        .collection(process.env.MONGODB_COLLECTION || 'pages');
      stage = 'browser navigation';
      await session.execute({ type: 'goto', url });
      stage = 'browser scrape';
      const markdown = await session.scrape();
      stage = 'MongoDB insert';
      const inserted = await collection.insertOne({ url, markdown, session_id: session.getId()! });
      console.log(inserted.insertedId.toHexString());
      documentId = inserted.insertedId.toHexString();
    } finally {
      try {
        await mongo.close();
      } catch {
        cleanupFailed = true;
      }
    }
    if (cleanupFailed) {
      stage = 'MongoDB cleanup';
      throw new Error('MongoDB disconnect failed');
    }
    return { document_id: documentId, session_id: session.getId()! };
  } catch (error) {
    const code = error instanceof MongoServerError && typeof error.code === 'number' ? error.code : undefined;
    const type = error instanceof Error ? error.name : 'UnknownError';
    throw new Error(`MongoDB export failed (session ${session.getId()!}, code ${code}): ${stage}: ${type}`);
  }
});
```

The example prints the inserted document ID. Each document contains the source URL, scraped Markdown, and Notte session ID. Set `MONGODB_DATABASE` and `MONGODB_COLLECTION` to choose the destination; they default to `notte` and `pages`.

See [scraping](https://docs.notte.cc/concepts/scraping.md) and [session lifecycle](https://docs.notte.cc/features/sessions/lifecycle.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.