Skip to contentManaged Kafka is live: Apache Kafka on AWS for half the cost of MSK

Sources

Connect MongoDB as a source

Connect a MongoDB replica set or sharded cluster to an Artie pipeline with a read-only user, and choose how Artie reads its change streams.

Artie reads MongoDB change streams and captures insert, update, replace, and delete operations.

Prerequisites

  • A MongoDB replica set or sharded cluster. Change streams don’t run on a standalone server, so convert it to a one-member replica set.
  • A direct network path from Artie. MongoDB sources don’t support SSH tunnels or PrivateLink, so add the fixed IP addresses for your data plane to your allowlist.
  • The connection string, in SRV (mongodb+srv://) or standard (mongodb://) format.
  • The name of the database to replicate.

For Amazon DocumentDB, follow the DocumentDB guide instead.

To find the connection string in Atlas, go to the Clusters page, select Connect for your cluster, and copy the connection string.

MongoDB connection string

Set up MongoDB

These steps cover the Source section of pipeline setup. If you reuse a MongoDB source from another pipeline, setup skips Prepare source.

  1. Choose MongoDB

    On Choose source, select MongoDB.

  2. Create a service account

    Artie reads change streams and backfills collections as this user. On Prepare source, under Hosting provider, select Atlas or Self-hosted / other.

    1. In Atlas, select Database Access in the left sidebar.
    2. Select Add New Database User.
    3. Under Database User Privileges, open Built-in Role and select Only read any database.

    To limit the user to one database, open Specific Privileges and select Add Specific Privilege. Add read on that database and on local. A user limited this way can’t use one change stream for the whole cluster, which needs readAnyDatabase.

    Select Continue.

  3. Connect and verify MongoDB

    On Connect and verify, fill in the connection settings. Every field except Snapshot read preference is required.

    SettingWhat to enter
    Connection stringThe SRV or standard connection string, without a user name or password. Artie rejects a connection string that contains a password.
    UserThe service account’s user name, artie in the script.
    PasswordThe service account’s password.
    Snapshot read preferenceThe read preference for backfill queries only: primary, primaryPreferred, secondary, secondaryPreferred, or nearest. Default (use connection string) keeps the connection string’s read preference.
    Database nameThe database to replicate.

    The connection string can’t contain # or any of these options:

    • authMechanism set to anything other than SCRAM-SHA-256 or SCRAM-SHA-1. Leave it unset to use SCRAM.
    • authMechanismProperties
    • Options that read a file: tlsCAFile, tlsCertificateKeyFile, tlsCertificateKeyFilePassword, tlsCertificateFile and tlsPrivateKeyFile, plus the older spellings sslCertificateAuthorityFile, sslClientCertificateKeyFile and sslClientCertificateKeyPassword
    • Proxy options: proxyHost, proxyPort, proxyUsername and proxyPassword

    A saved source that has any of these options fails verification and can’t connect. Remove them in Settings → Connectors.

    If the connection string sets tls=false or ssl=false, the form warns that the connection isn’t encrypted. A reused source shows its saved settings instead; edit its credentials in Settings → Connectors.

    Select Verify source. The step shows Source verified when the check passes. Select Continue.

Change stream settings

By default, Artie requests each document’s pre-image. Enabling full document before change covers the MongoDB command that turns pre-images on. The four toggles after it are optional and off by default.

Find the toggles in one of two places:

  • During setup: on Connect and verify, expand Advanced options and find the Change stream group.
  • On the pipeline page: open the Source: MongoDB tab and expand Advanced settings.

During setup, the toggles are read-only when the pipeline uses a reader that another pipeline owns. The sections below use the pipeline page labels. Setup labels them differently:

Pipeline pagePipeline setup
Disable full document before changeSkip document before change
Enable client-side full document lookupClient-side document lookup
Use one change stream per collectionOne change stream per collection
Use one change stream for the whole clusterOne change stream for the whole cluster

Enabling full document before change

Artie asks MongoDB for each document as it was before the change. MongoDB sends this pre-image only for collections with pre-images enabled. Without one, a delete event carries only the document’s _id.

Pre-images require MongoDB 6.0 or later. Enable them on a collection that lands in a partitioned destination table. Artie needs the deleted document’s partition fields to select the right partition.

Run this command in the MongoDB shell to enable pre-images on the collection:

JavaScript
use DATABASE_NAME;
db.runCommand({ collMod: "COLLECTION_NAME", changeStreamPreAndPostImages: { enabled: true } });

Replace DATABASE_NAME and COLLECTION_NAME with the database and collection you replicate.

By default, MongoDB keeps a pre-image until its change stream event leaves the oplog. To keep pre-images for a set time instead, set expireAfterSeconds. Keep them at least as long as you might pause the pipeline. A pre-image that expires before Artie reads it arrives as _id only.

On a self-hosted deployment, this command, run in the MongoDB shell, keeps pre-images for 24 hours (86,400 seconds):

JavaScript
use admin;
db.runCommand({
   setClusterParameter: {
      changeStreamOptions: {
         preAndPostImages: {
            expireAfterSeconds: 86400
         }
      }
   }
});

To check the retention setting on a self-hosted deployment, run:

JavaScript
db.adminCommand( { getClusterParameter: "changeStreamOptions" } );

To return a self-hosted deployment to the default retention, set expireAfterSeconds to 'off':

JavaScript
use admin;
db.runCommand( {
   setClusterParameter:
      { changeStreamOptions: {
         preAndPostImages: { expireAfterSeconds: 'off' }
      } }
} );

Atlas doesn’t support setClusterParameter. On Atlas, set the cluster’s changeStreamOptionsPreAndPostImagesExpireAfterSeconds option with the Atlas Administration API’s update advanced configuration endpoint instead, and read it back with return advanced configuration. Set it to -1, its default, to return to the default retention.

Disable full document before change

Turn on Disable full document before change if your MongoDB deployment doesn’t support fullDocumentBeforeChange. Artie then opens the change stream without that option.

Enable client-side full document lookup

By default, Artie asks MongoDB to attach the full document to each update event. When the document plus the event’s metadata exceeds the 16 MB BSON limit, the read fails with a BSONObjectTooLarge error.

With Enable client-side full document lookup on, Artie fetches the document itself with a FindOne query for each update event.

Use one change stream per collection

With Use one change stream per collection on, Artie opens a change stream for each selected collection. It stores a separate resume token for each stream and fetches from up to 5 streams at a time.

Ordering is preserved within a collection, not across collections. All streams share the same reader.

Change this setting only while the pipeline is in draft or paused. On a pipeline that is already streaming, switching requires backfilling the selected collections. The existing resume token doesn’t carry over to per-collection streams.

This setting can’t be on together with Use one change stream for the whole cluster.

Use one change stream for the whole cluster

With Use one change stream for the whole cluster on, Artie streams collections from every database through one change stream. Pick collections from any database.

The setting has these requirements and effects:

  • It needs MongoDB 4.0 or later.
  • The service account needs the readAnyDatabase role.
  • Destination tables are named <database>_<collection>.
  • One cursor carries every selected collection, so that stream caps throughput.

Change this setting only while the pipeline is in draft or paused. Artie rejects the change if it renames a destination table the pipeline already writes to. On a pipeline that is already streaming, switching requires backfilling the selected collections, because the resume token doesn’t carry over.

This setting can’t be on together with Use one change stream per collection.

Plan for high-throughput collections

MongoDB writes every change on a replica set to one oplog. A change stream is a cursor over that oplog. On a sharded cluster, each shard has its own oplog, and mongos merges them into one ordered stream.

One change stream per pipeline

By default, Artie opens a single database-level change stream for the pipeline. It filters on the server to the collections you selected and the insert, update, replace, and delete operations. Events come back in oplog order across all selected collections.

A write spike in one selected collection delays the others. Suppose orders takes 10,000 writes per second and users takes one write every few seconds. A users change written after an orders burst waits until Artie reads and processes every orders event ahead of it.

Each update also triggers a full document lookup by _id, so a busy collection adds read load as well.

Collections you did not select

MongoDB drops their oplog entries on the server, so they are not sent to Artie or looked up. The cursor still reads past those entries. A write burst anywhere on the replica set adds latency, but less than a busy selected collection does.

Oplog window

The oplog is a capped collection, so heavy writes on any collection shrink how much history it holds. A pipeline falls behind during a destination outage or a long pause. If it falls further behind than the oplog window, its resume token is no longer in the oplog.

The affected collections must then be backfilled again. Size the oplog for your peak write rate, or set oplogMinRetentionHours on MongoDB 4.4 or later.

Isolate a busy collection

Choose one of two options:

  1. Move the busy collection into its own pipeline. It gets its own change stream and its own reader, so spikes there do not delay any other collection.
  2. Turn on Use one change stream per collection. Each collection gets its own change stream, and all streams share one reader.

Each change stream reads the oplog separately on the server. Splitting collections stops one from waiting behind another, but it adds read load on the replica set.

Data types and nested fields

MongoDB collections have no enforced schema, so Artie builds each destination table’s columns from the documents it reads.

  • Data types: Artie takes each field’s type from its first non-null value and maps that BSON type to a destination column type.
  • Mixed-type fields: The column keeps its first type. If a later document holds a value that can’t convert to it, such as age: "twenty-five" in an integer column, the flush fails. Cast all columns to string prevents this for columns discovered later. For a column that already fails, also rebuild the table.
  • Sparse or dynamic fields: Artie unions the schema across all observed documents. A field that a document lacks is written as NULL.
  • Nested objects: Nested documents and arrays stay JSON objects in the destination by default.

To write nested fields as their own columns, turn on Flatten nested documents for the collection.

For example, suppose the source document contains:

JSON
{
  "test_nested_object": {
    "a": {"b": {"c": "hello"}},
    "test_timestamp": {"$timestamp": { "t": 1678929517, "i": 1 }},
    "super_nested": {
      "test_timestamp": {"$timestamp": { "t": 1678929517, "i": 1 }},
      "foo": "bar"
    }
  }
}

Artie outputs test_nested_object as:

JSON
{
  "a": {
    "b": {
      "c": "hello"
    }
  },
  "super_nested": {
    "foo": "bar",
    "test_timestamp": "2023-03-16T01:18:37Z"
  },
  "test_timestamp": "2023-03-16T01:18:37Z"
}

Artie converts BSON-specific types such as $timestamp to standard formats. If Artie writes JSON to a text column in the destination, it stores the nested object as a JSON string. For example, it does this for SQL Server, Oracle and Delta, for Databricks without JSON as VARIANT, and for Redshift with JSON as VARCHAR on.

Cast all columns to string

With Cast all columns to string on, Artie stores every column as a string as it is discovered, whatever its BSON type. That includes the primary key. Nested objects are stored as JSON strings. System columns (__artie_*) keep their own types.

The setting applies to new columns as they are discovered. Existing destination columns keep their types. To cast every column on a pipeline with an existing destination table, rebuild the table after you turn the setting on.

Kafka destinations don’t have this setting. For other destinations, find it in one of two places:

  • During setup: the destination’s Connect and verify step, under Advanced options.
  • On the pipeline page: the destination tab, under Advanced settings.

Next steps

Was this page helpful?