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

# Run the MongoDB Connector Externally

> Configure MongoDB ingestion via YAML to extract collection metadata, schema, and profiling insights from NoSQL datasets.

![MongoDB](https://docs.open-metadata.org/public/images/connectors/mongodb.webp)

# MongoDB

PROD

In this section, we provide guides and references to use the MongoDB connector.
Configure and schedule MongoDB metadata workflows from the OpenMetadata UI:

* [Requirements](#requirements)
* [Metadata Ingestion](#metadata-ingestion)
* [Data Profiler](#data-profiler)

## How to Run the Connector Externally

To run the Ingestion via the UI you'll need to use the OpenMetadata Ingestion Container, which comes shipped with
custom Airflow plugins to handle the workflow deployment.

If, instead, you want to manage your workflows externally on your preferred orchestrator, you can check
the following docs to run the Ingestion Framework **anywhere**.

> [card] [External Schedulers](https://docs.open-metadata.org/v2.1.x/deployment/ingestion.md)
>
> Get more information about running the Ingestion Framework Externally

## Requirements

To fetch the metadata from MongoDB to OpenMetadata, the MongoDB user must have access to perform `find` operation on collection and `listCollection` operations on database available in MongoDB.

### Python Requirements

Use Python 3.10 or later. Python 3.12 is recommended, because it is what the OpenMetadata 2.0 ingestion images use. To confirm the supported range for your release, check the `Requires-Python` metadata of that release’s `openmetadata-ingestion` package.

To run the MongoDB ingestion, you will need to install:

```bash theme={null}
pip3 install "openmetadata-ingestion[mongo]"
```

## Metadata Ingestion

All connectors are defined as JSON Schemas.
[Here](https://github.com/open-metadata/OpenMetadata/blob/main/openmetadata-spec/src/main/resources/json/schema/entity/services/connections/database/mongoDBConnection.json)
you can find the structure to create a connection to MongoDB.
In order to create and run a Metadata Ingestion workflow, we will follow
the steps to create a YAML configuration able to connect to the source,
process the Entities if needed, and reach the OpenMetadata server.
The workflow is modeled around the following
[JSON Schema](https://github.com/open-metadata/OpenMetadata/blob/main/openmetadata-spec/src/main/resources/json/schema/metadataIngestion/workflow.json)

### 1. Define the YAML Config

This is a sample config for MongoDB:

#### Source Configuration

Configure the source type and service name for your MongoDB connector.

#### Username

**username**: Username to connect to Mongodb. This user must have access to perform `find` operation on collection and `listCollection` operations on database available in MongoDB.

#### Password

**password**: Password to connect to MongoDB.

#### Host Port

**hostPort**: When using the `mongodb` connecion schema, the hostPort parameter specifies the host and port of the MongoDB. This should be specified as a string in the format `hostname:port`. E.g., `localhost:27017`. When using the `mongodb+srv` connection schema, the hostPort parameter specifies the host and port of the MongoDB. This should be specified as a string in the format `hostname`. E.g., `cluster0-abcde.mongodb.net`.

Using Atlas? Follow [this guide](https://www.mongodb.com/docs/atlas/driver-connection/) to get the connection string.

#### Database Name

**databaseName**: Optional name to give to the database in OpenMetadata. If left blank, we will use default as the database name.

#### Connection Options

#### Advanced Configuration

**Connection Options (Optional)**: Enter the details for any additional connection options that can be sent to database during the connection. These details must be added as Key-Value pairs.

#### Source Config

The `sourceConfig` is defined [here](https://github.com/open-metadata/OpenMetadata/blob/main/openmetadata-spec/src/main/resources/json/schema/metadataIngestion/databaseServiceMetadataPipeline.json):

* **markDeletedTables**: To flag tables as soft-deleted if they are not present anymore in the source system.
* **markDeletedStoredProcedures**: Optional configuration to soft delete stored procedures in OpenMetadata if the source stored procedures are deleted. Also, if the stored procedure is deleted, all the associated entities like lineage, etc., with that stored procedure will be deleted.
* **markDeletedSchemas**: Optional configuration to soft delete schemas stored in OpenMetadata if the source schema is deleted. Setting this flag to true will only keep filtered schemas and delete any other schemas that do not match schemaFilterPattern or do not exist at source.
* **markDeletedDatabases**: Additional optional configuration for soft deletion, providing a granular option to select which particular entities should be deleted.
* **includeTables**: Set to `true` or `false` to ingest table data. Default is `true`.
* **includeViews**: Set to `true` or `false` to ingest view definitions.
* **includeTags**: Optional configuration to toggle the tags ingestion.
* **includeOwners**: Set the **Include Owners** toggle to control whether to include owners to the ingested entity if the owner email matches with a user stored in the OM server as part of metadata ingestion. If the ingested entity already exists and has an owner, the owner will not be overwritten.
* **ownerConfig**: Advanced, hierarchical configuration for assigning owners to databases, schemas, and tables during ingestion, with per-entity mappings and inheritance. For more information, see [Hierarchical Owner Configuration](https://docs.open-metadata.org/connectors/ingestion/workflows/metadata/hierarchical-owner-configuration).
* **includeStoredProcedures**: Optional configuration to toggle the Stored Procedures ingestion.
* **includeDDL**: Optional configuration to toggle the DDL Statements ingestion.
* **overrideMetadata** *(boolean)*: Set the **Override Metadata** toggle to control whether to override the existing metadata in the OpenMetadata server with the metadata fetched from the source. If the toggle is set to true, the metadata fetched from the source will override the existing metadata in the OpenMetadata server. If the toggle is set to false, the metadata fetched from the source will not override the existing metadata in the OpenMetadata server. This is applicable for fields like description, tags, owner, and displayName.
* **queryLogDuration**: Configuration to tune how far we want to look back in query logs to process Stored Procedures results.
* **queryParsingTimeoutLimit**: Configuration to set the timeout for parsing the query in seconds.
* **useFqnForFiltering**: Regex will be applied on the fully qualified name (for example, `service_name.db_name.schema_name.table_name`) instead of the raw name (for example, `table_name`).
* **databaseFilterPattern**, **schemaFilterPattern**: Note that the filter supports regex as include or exclude. You can find examples [here](https://docs.open-metadata.org/connectors/ingestion/workflows/metadata/filter-patterns/database).
* **tableFilterPattern**: Note that the filter supports regex as include or exclude. You can find examples [here](https://docs.open-metadata.org/connectors/ingestion/workflows/metadata/filter-patterns/table).
* **threads (beta)**: The number of threads to use when extracting the metadata using multithreading.
* **databaseMetadataConfigType** *(string)*: Database Source Config Metadata Pipeline type.
* **incremental (beta)**: Incremental Extraction configuration. Currently implemented for [BigQuery](https://docs.open-metadata.org/connectors/ingestion/workflows/metadata/incremental-extraction/bigquery), [Redshift](https://docs.open-metadata.org/connectors/ingestion/workflows/metadata/incremental-extraction/redshift), and [Snowflake](https://docs.open-metadata.org/connectors/ingestion/workflows/metadata/incremental-extraction/snowflake).

#### Sink Configuration

To send the metadata to OpenMetadata, it needs to be specified as `type: metadata-rest`.

#### Workflow Configuration

The main property here is `openMetadataServerConfig`, where you can define the host and security provider of your OpenMetadata installation.

* **loggerLevel**: Specify the logger level depending on your needs. If you are troubleshooting an ingestion, use `DEBUG` for more detailed traces.
* **JWT token**: JWT tokens allow clients to authenticate against the OpenMetadata server. See [Enable JWT Tokens](https://docs.open-metadata.org/deployment/security/enable-jwt-tokens) and [JWT Troubleshooting](https://docs.open-metadata.org/deployment/security/jwt-troubleshooting) for more information.
* **storeServiceConnection**: If set to `true` (default), sensitive information is stored encrypted with the Fernet Key or externally if you have configured a [Secrets Manager](https://docs.open-metadata.org/deployment/secrets-manager). If set to `false`, the service is created, but the service connection information is only used by the Ingestion Framework at runtime and is not sent to the OpenMetadata server.
* **SSL configuration**: If you have added SSL to the [OpenMetadata server](https://docs.open-metadata.org/deployment/security/enable-ssl), configure the certificates for ingestion. Set `verifySSL` to `ignore`, or set it to `validate` and provide `sslConfig.caCertificate` with a local path to the server certificate. See [SSL Troubleshooting](https://docs.open-metadata.org/deployment/security/enable-ssl/ssl-troubleshooting) for more information.
* **ingestionPipelineFQN**: Fully qualified name of the ingestion pipeline, used to identify the current ingestion pipeline.

mongodb\_config.yaml
Copy full code

```yaml theme={null}
source:
  type: mongodb
  serviceName: local_mongodb
  serviceConnection:
    config:
      type: MongoDB
      username: username
      password: password
      hostPort: localhost:27017
      # connectionOptions:
      #   key: value
      databaseName: custom_database_name
```

```yaml theme={null}
  sourceConfig:
    config:
      type: DatabaseMetadata
      markDeletedTables: true
      markDeletedStoredProcedures: true
      markDeletedSchemas: true
      markDeletedDatabases: true
      includeTables: true
      includeViews: true
      # includeTags: true
      # includeOwners: false
      # ownerConfig:
      #   default: data-platform-team
      #   database:
      #     database1: owner1
      #   databaseSchema:
      #     database1.schema1: owner1
      #   table:
      #     database1.schema1.table1: owner1
      #   enableInheritance: true
      # includeStoredProcedures: true
      # includeDDL: true
      # overrideMetadata: false
      # queryLogDuration: 1
      # queryParsingTimeoutLimit: 300
      # useFqnForFiltering: false
      # threads: 1
      # databaseMetadataConfigType: ()
      # incremental:
      #   enabled: true
      #   lookbackDays: 7
      #   safetyMarginDays: 1
      # databaseFilterPattern:
      #   includes:
      #     - database1
      #     - database2
      #   excludes:
      #     - database3
      #     - database4
      # schemaFilterPattern:
      #   includes:
      #     - schema1
      #     - schema2
      #   excludes:
      #     - schema3
      #     - schema4
      # tableFilterPattern:
      #   includes:
      #     - users
      #     - type_test
      #   excludes:
      #     - table3
      #     - table4
```

```yaml theme={null}
sink:
  type: metadata-rest
  config: {}
```

```yaml theme={null}
workflowConfig:
  loggerLevel: INFO  # DEBUG, INFO, WARNING or ERROR
  openMetadataServerConfig:
    hostPort: "http://localhost:8585/api"
    authProvider: openmetadata
    securityConfig:
      jwtToken: "{bot_jwt_token}"
    ## Store the service Connection information
    storeServiceConnection: true  # false
    ## Secrets Manager Configuration
    # secretsManagerProvider: aws, azure or noop
    # secretsManagerLoader: airflow or env
    ## If SSL, fill the following
    # verifySSL: validate  # or ignore
    # sslConfig:
    #   caCertificate: /local/path/to/certificate
# ingestionPipelineFQN: <service name>.<ingestion name> ## e.g., "my_redshift.metadata"
```

### 2. Run with the CLI

First, we will need to save the YAML file. Afterward, and with all requirements installed, we can run:

```bash theme={null}
metadata ingest -c <path-to-yaml>
```

Note that from connector to connector, this recipe will always be the same. By updating the YAML configuration,
you will be able to extract metadata from different sources.

## Data Profiler

The Data Profiler workflow will be using the `orm-profiler` processor.
After running a Metadata Ingestion workflow, we can run Data Profiler workflow.
While the `serviceName` will be the same to that was used in Metadata Ingestion, so the ingestion bot can get the `serviceConnection` details from the server.

### Limitations

The MongodDB data profiler current supports only the following features:

1. **Row count**: The number of rows in the collection. Sampling or custom query is not supported.
2. **Sample data:** If a custom query is defined it will be used for sample data.

### 1. Define the YAML Config

This is a sample config for the profiler:

#### Source Configuration

#### Source Configuration - Source Config

You can find all the definitions and types for the  `sourceConfig` [here](https://github.com/open-metadata/OpenMetadata/blob/main/openmetadata-spec/src/main/resources/json/schema/metadataIngestion/databaseServiceProfilerPipeline.json).

**generateSampleData**: Option to turn on/off generating sample data.

#### Process PII Sensitive

**processPiiSensitive**: Optional configuration to automatically tag columns that might contain sensitive information.

#### Timeout Seconds

**timeoutSeconds**: Profiler Timeout in Seconds

#### Schema Filter Pattern

**schemaFilterPattern**: Regex to only fetch tables or databases that matches the pattern.

#### Table Filter Pattern

**tableFilterPattern**: Regex to only fetch tables or databases that matches the pattern.

#### Processor Configuration

#### Processor Configuration

Choose the `orm-profiler`. Its config can also be updated to define tests from the YAML itself instead of the UI:

**tableConfig**: `tableConfig` allows you to set up some configuration at the table level.

#### Sink Configuration

#### Sink Configuration

To send the metadata to OpenMetadata, it needs to be specified as `type: metadata-rest`.

#### Workflow Configuration

#### Workflow Configuration

The main property here is the `openMetadataServerConfig`, where you can define the host and security provider of your OpenMetadata installation.

For a simple, local installation using our docker containers, this looks like:

mongodb\_profiler\_config.yaml
Copy full code

```yaml theme={null}
source:
  type: monogodb
  serviceName: local_mongodb
  sourceConfig:
    config:
      type: Profiler
      generateSampleData: true
      processPiiSensitive: false
      # timeoutSeconds: 43200
      # schemaFilterPattern:
      #   includes:
      #     - schema1
      #     - schema2
      #   excludes:
      #     - schema3
      #     - schema4
      # tableFilterPattern:
      #   includes:
      #     - table1
      #     - table2
      #   excludes:
      #     - table3
      #     - table4
processor:
  type: orm-profiler
  config: {}  # Remove braces if adding properties
    # tableConfig:
    #   - fullyQualifiedName: <table fqn>
    #     profileQuery: <query to use for fetching the sample data>
sink:
  type: metadata-rest
  config: {}
workflowConfig:
  # loggerLevel: DEBUG  # DEBUG, INFO, WARN or ERROR
  openMetadataServerConfig:
    hostPort: <OpenMetadata host and port>
    authProvider: <OpenMetadata auth provider>
```

* You can learn more about how to configure and run the Profiler Workflow to extract Profiler data and execute the Data Quality from [here](https://docs.open-metadata.org/v2.1.x/how-to-guides/data-quality-observability/profiler/profiler-workflow.md)

### 2. Prepare the Profiler DAG

Here, we follow a similar approach as with the metadata and usage pipelines, although we will use a different Workflow class:

#### Import Necessary Modules

#### Import necessary modules

The `ProfilerWorkflow` class that is being imported is a part of a metadata orm\_profiler framework, which defines a process of extracting Profiler data.

Here we are also importing all the basic requirements to parse YAMLs, handle dates and build our DAG.

#### Default Arguments

**Default arguments for all tasks in the Airflow DAG.**

* Default arguments dictionary contains default arguments for tasks in the DAG, including the owner's name, email address, number of retries, retry delay, and execution timeout.

#### Config

* **config**: Specifies config for the profiler as we prepare above.

#### Workflow Function

* **metadata\_ingestion\_workflow()**: This code defines a function `metadata_ingestion_workflow()` that loads a YAML configuration, creates a `ProfilerWorkflow` object, executes the workflow, checks its status, prints the status to the console, and stops the workflow.

#### DAG Definition

* **DAG**: creates a DAG using the Airflow framework, and tune the DAG configurations to whatever fits with your requirements
* For more Airflow DAGs creation details visit [here](https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/dags.html#declaring-a-dag).

mongodb\_profiler\_dag.py
Copy full code

```python theme={null}
import pathlib
import yaml
from datetime import timedelta
from airflow import DAG

from metadata.profiler.api.workflow import ProfilerWorkflow

default_args = {
    "owner": "user_name",
    "email": ["username@org.com"],
    "execution_timeout": timedelta(minutes=60),
    "retries": 3,
    "retry_delay": timedelta(minutes=5),
}

config = """
<your YAML configuration>
"""

def metadata_ingestion_workflow():
    workflow_config = yaml.safe_load(config)
    workflow = ProfilerWorkflow.create(workflow_config)
    workflow.execute()
    workflow.raise_from_status()
    workflow.print_status()
    workflow.stop()

with DAG(
    "profiler_example",
    default_args=default_args,
    description="An example DAG which runs the ProfilerWorkflow",
    start_date=datetime(2021, 1, 1),
    is_paused_upon_creation=False,
    catchup=False,
) as dag:
    ingest_task = PythonOperator(
        task_id="profile_and_test_using_recipe",
        python_callable=metadata_ingestion_workflow,
    )
```

## dbt Integration

> [card] [dbt Integration](https://docs.open-metadata.org/v2.1.x/connectors/database/dbt.md)
>
> Learn more about how to ingest dbt models


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