

# Managing Amazon DocumentDB resources
<a name="managing-documentdb"></a>

These sections cover the various components and their related tasks for managing your Amazon DocumentDB (with MongoDB compatibility) implementation.

**Topics**
+ [Operational tasks overview](operational_tasks.md)
+ [Global clusters](global-clusters.md)
+ [Managing clusters](db-clusters.md)
+ [Managing instances](db-instances.md)
+ [Managing subnet groups](document-db-subnet-groups.md)
+ [High availability and replication](replication.md)
+ [Managing indexes](managing-indexes.md)
+ [Managing document compression](doc-compression.md)
+ [Managing dictionary-based compression](dict-compression.md)
+ [Managing events](managing-events.md)
+ [

# Choosing regions and availability zones
](regions-and-azs.md)
+ [Managing cluster parameter groups](cluster_parameter_groups.md)
+ [Understanding endpoints](endpoints.md)
+ [Understanding Amazon DocumentDB ARNs](documentdb-arns.md)
+ [Tagging resources](tagging.md)
+ [Maintaining Amazon DocumentDB](db-instance-maintain.md)
+ [

# Understanding service-linked roles
](service-linked-roles.md)
+ [Using change streams](change_streams.md)
+ [Using Collation](collation.md)
+ [Using Views](views.md)
+ [

# Using AWS Lambda with change streams
](using-lambda.md)

# Amazon DocumentDB Operational tasks overview
<a name="operational_tasks"></a>

This section covers operational tasks for your Amazon DocumentDB cluster, and how to accomplish these tasks using the AWS CLI.

**Topics**
+ [

## Adding a replica to an Amazon DocumentDB cluster
](#operational_tasks-add_replica)
+ [

## Describing clusters and instances
](#operational_tasks-list_clusters_and_instances)
+ [

## Creating a cluster snapshot
](#operational_tasks-creating_snapshot)
+ [

## Restoring from a snapshot
](#operational_tasks-restore_from_snapshot)
+ [

## Removing an instance from a cluster
](#operational_tasks-remove_instance_from_cluster)
+ [

## Deleting a cluster
](#operational_tasks-delete_cluster)

## Adding a replica to an Amazon DocumentDB cluster
<a name="operational_tasks-add_replica"></a>

After you create the primary instance for your Amazon DocumentDB cluster, you can add one or more *replicas*. A replica is a read-only instance that serves two purposes:
+ **Scalability** — If you have a large number of clients that require concurrent access, you can add more replicas for read-scaling.
+ **High availability** — If the primary instance fails, Amazon DocumentDB automatically fails over to a replica instance and designates it as the new primary. If a replica fails, other instances in the cluster can still serve requests until the failed node can be recovered. 

Each Amazon DocumentDB cluster can support up to 15 replicas.

**Note**  
For maximum fault tolerance, you should deploy replicas in separate Availability Zones. This helps ensure that your Amazon DocumentDB cluster can continue to function, even if an entire Availability Zone becomes unavailable.

The following AWS CLI example shows how to add a new replica. The `--availability-zone` parameter places the replica in the specified Availability Zone.

```
aws docdb create-db-instance \
    --db-instance-identifier sample-instance \
    --db-cluster-identifier sample-cluster \
    --engine docdb \
    --db-instance-class db.r5.large \
    --availability-zone us-east-1a
```

## Describing clusters and instances
<a name="operational_tasks-list_clusters_and_instances"></a>

The following AWS CLI example lists all Amazon DocumentDB clusters in a Region. For certain management features such as cluster and instance lifecycle management, Amazon DocumentDB leverages operational technology that is shared with Amazon RDS. The `filterName=engine,Values=docdb` filter parameter returns only Amazon DocumentDB clusters. 

For more information on describing and modifying clusters, see the [Amazon DocumentDB cluster lifecycle](db-cluster-life-cycle.md).

```
aws docdb describe-db-clusters --filter Name=engine,Values=docdb
```

Output from this operation looks something like the following.

```
{
    "DBClusters": [
        {
            "AvailabilityZones": [
                "us-east-1c",
                "us-east-1b",
                "us-east-1a"
            ],
            "BackupRetentionPeriod": 1,
            "DBClusterIdentifier": "sample-cluster-1",
            "DBClusterParameterGroup": "sample-parameter-group",
            "DBSubnetGroup": "default",
            "Status": "available",
            ...
        },
        {
            "AvailabilityZones": [
                "us-east-1c",
                "us-east-1b",
                "us-east-1a"
            ],
            "BackupRetentionPeriod": 1,
            "DBClusterIdentifier": "sample-cluster-2",
            "DBClusterParameterGroup": "sample-parameter-group",
            "DBSubnetGroup": "default",
            "Status": "available",
            ...
        },
        {
            "AvailabilityZones": [
                "us-east-1c",
                "us-east-1b",
                "us-east-1a"
            ],
            "BackupRetentionPeriod": 1,
            "DBClusterIdentifier": "sample-cluster-3",
            "DBClusterParameterGroup": "sample-parameter-group",
            "DBSubnetGroup": "default",
            "Status": "available",
            ...
        }
    ]
}
```

The following AWS CLI example lists the instances in an Amazon DocumentDB cluster. For more information on describing and modifying clusters, see the [Amazon DocumentDB instance lifecycle](db-instance-life-cycle.md). 

```
aws docdb describe-db-clusters \
    --db-cluster-identifier sample-cluster \
    --query 'DBClusters[*].[DBClusterMembers]'
```

The output looks like something like below. In this output, there are two instances. The primary instance is `sample-instance-1` (`"IsClusterWriter": true`). There is also a replica instance, `sample-instance2` (`"IsClusterWriter: false"`).

```
[
    [
        [
            {
                "DBInstanceIdentifier": "sample-instance-1",
                "IsClusterWriter": true,
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1
            },
            {
                "DBInstanceIdentifier": "sample-cluster-2",
                "IsClusterWriter": false,
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1
            }
        ]
    ]
]
```

## Creating a cluster snapshot
<a name="operational_tasks-creating_snapshot"></a>

A *cluster snapshot* is a complete backup of the data in your Amazon DocumentDB cluster. When the snapshot is being created, Amazon DocumentDB reads your data directly from the cluster volume. Because of this, you can create a snapshot even if your cluster doesn't have any instances running at the time. The amount of time it takes to create a snapshot depends on the size of your cluster volume.

Amazon DocumentDB supports automatic backups, which occur daily during the preferred backup window — a 30-minute period of time during the day. The following AWS CLI example shows how to view the backup window for your cluster:

```
aws docdb describe-db-clusters \
    --db-cluster-identifier sample-cluster \
    --query 'DBClusters[*].PreferredBackupWindow'
```

The output shows the backup window (in UTC):

```
[
    "00:18-00:48"
]
```

You can define the backup window when you create your Amazon DocumentDB cluster. You can also change the backup window, as shown in the following example. If you don't define a backup window, Amazon DocumentDB automatically assigns one to your cluster.

```
aws docdb modify-db-cluster \
    --db-cluster-identifier sample-cluster \
    --preferred-backup-window "02:00-02:30"
```

In addition to automatic backups, you can manually create a cluster snapshot at any time. When you do this, you specify which cluster you want to back up, and a unique name for your snapshot so that you can restore from it later.

The following AWS CLI example shows how to create a snapshot of your data.

```
aws docdb create-db-cluster-snapshot \
    --db-cluster-identifier sample-cluster \
    --db-cluster-snapshot-identifier sample-cluster-snapshot
```

## Restoring from a snapshot
<a name="operational_tasks-restore_from_snapshot"></a>

You can restore a cluster snapshot to a new Amazon DocumentDB cluster. To do this, you provide the name of the snapshot and the name of a new cluster. You can't restore from a snapshot to an existing cluster; instead, Amazon DocumentDB creates a new cluster when you restore and then populates it with your snapshot data. 

The following example shows all the snapshots for the cluster `sample-cluster`.

```
aws docdb describe-db-cluster-snapshots \
    --db-cluster-identifier sample-cluster \
    --query 'DBClusterSnapshots[*].[DBClusterSnapshotIdentifier,SnapshotType,Status]'
```

The output looks something like the following. A manual snapshot is one that you created manually, whereas an automated snapshot is created by Amazon DocumentDB within the cluster backup window.

```
[
        "sample-cluster-snapshot", 
        "manual", 
        "available"
    ], 
    [
        "rds:sample-cluster", 
        "automated", 
        "available"
    ]
]
```

The following example shows how to restore an Amazon DocumentDB cluster from a snapshot.

```
aws docdb restore-db-cluster-from-snapshot \
    --engine docdb \
    --db-cluster-identifier new-sample-cluster \
    --snapshot-identifier sample-cluster-snapshot
```

The new cluster does not have any instances associated with it; so if you want to interact with the cluster, you must add an instance to it.

```
aws docdb create-db-instance \
    --db-instance-identifier new-sample-instance \
    --db-instance-class db.r5.large \
    --engine docdb \
    --db-cluster-identifier new-sample-cluster
```

You can use the following AWS CLI operations to monitor the progress of cluster and instance creation. When the cluster and instance statuses are available, you can connect to the new cluster's endpoint and access your data.

```
aws docdb describe-db-clusters \
    --db-cluster-identifier new-sample-cluster  \
    --query 'DBClusters[*].[Status,Endpoint]'
```

```
aws docdb describe-db-instances \
    --db-instance-identifier new-sample-instance \
    --query 'DBInstances[*].[DBInstanceStatus]'
```

## Removing an instance from a cluster
<a name="operational_tasks-remove_instance_from_cluster"></a>

Amazon DocumentDB stores all of your data in the cluster volume. The data persists in that cluster volume, even if you remove all the instances from your cluster. If you need to access the data again, you can add an instance to the cluster at any time, and pick up where you left off.

The following example shows how to remove an instance from your Amazon DocumentDB cluster.

```
aws docdb delete-db-instance \
    --db-instance-identifier sample-instance
```

## Deleting a cluster
<a name="operational_tasks-delete_cluster"></a>

Before you can delete an Amazon DocumentDB cluster, you must first remove all of its instances. The following AWS CLI example returns information about the instances in a cluster. If this operation returns any instance identifiers, you have to delete each of the instances. For more information, see [Removing an instance from a cluster](#operational_tasks-remove_instance_from_cluster). 

```
aws docdb describe-db-clusters \
    --db-cluster-identifier sample-cluster \
    --query 'DBClusters[*].DBClusterMembers[*].DBInstanceIdentifier'
```

When there are no more instances remaining, you can delete the cluster. At that time, you must choose one of the following options:
+ **Create a final snapshot** — Capture all the cluster data in a snapshot so that you can re-create a new instance with that data later. The following example shows how to do this:

  ```
  aws docdb delete-db-cluster \
      --db-cluster-identifier sample-cluster \
      --final-db-snapshot-identifier sample-cluster-snapshot
  ```
+ **Skip the final snapshot** — Permanently discard all the cluster data. This cannot be reversed. The following example shows how to do this:

  ```
  aws docdb delete-db-cluster \
      --db-cluster-identifier sample-cluster \
      --skip-final-snapshot
  ```

# Overview of Amazon DocumentDB global clusters
<a name="global-clusters"></a>

## What is a global cluster?
<a name="w2aac35b9b3"></a>

A global cluster consists of one primary region and up to 10 read-only secondary regions. You issue write operations directly to the primary cluster in the primary region and Amazon DocumentDB automatically replicates the data to the secondary regions using dedicated infrastructure. Latency is typically under a second.

## How are global clusters useful?
<a name="w2aac35b9b5"></a>
+ **Recovery from region-wide outages ** — In the event of a region-wide outage, you can promote one of the secondary clusters to a primary cluster within minutes, with a typical Recovery Time Objective (RTO) of under a minute. The Recovery Point Objective (RPO) is typically measured in seconds, but this depends on the lag across the network at the time of the failure.
+ **Global reads with local latency ** — If you have offices around the world, you can use a global cluster to keep your main sources of information updated in the primary region. Offices in your other regions can access the information in their own region, with local latency.
+ **Scalable secondary clusters ** — You can scale your secondary clusters by adding more read-only instances to a secondary region. The secondary cluster is read-only, so it can support up to 16 read-only replica instances rather than the usual limit of 15 for a single cluster.
+ **Fast replication from primary to secondary clusters** — The replication performed by a global cluster has little performance impact on the primary database cluster. The resources of the DB instances are fully devoted to serve application read and write workloads.

## What are the current limitations of global clusters?
<a name="w2aac35b9b7"></a>
+ Global clusters are not supported on Amazon DocumentDB v3.6.
+ Global clusters are supported on all instance types except db.t3, db.t4g, and db.r4.
+ Global clusters are not available in the following Regions: South America (São Paulo), Europe (Milan), China (Beijing), and China (Ningxia).
+ Switchover and global failover are not supported when regions are on different engine versions. Manual failover is supported when there's an engine version mismatch.
+ Only the primary cluster performs write operations. Clients that perform write operations connect to the cluster endpoint of the primary cluster.
+ You can have a maximum of 10 secondary regions and one primary region for your cluster.
+ A secondary cluster cannot be stopped. A primary cluster cannot be stopped if it has secondary clusters associated with it. Only a regional cluster that has no secondary clusters can be stopped.
+ Replicas attached to the secondary cluster can restart under certain circumstances. If the primary region's instance restarts or fails over, replicas in the secondary region also restart. The cluster is then unavailable until all replicas are back in sync with the primary database cluster's writer instance. This behavior is expected. Be sure that you understand the impact to your global cluster before making changes to your primary cluster.
+ You cannot use change streams on secondary clusters.

**Topics**
+ [

## What is a global cluster?
](#w2aac35b9b3)
+ [

## How are global clusters useful?
](#w2aac35b9b5)
+ [

## What are the current limitations of global clusters?
](#w2aac35b9b7)
+ [Quick start guide](global-clusters.get-started.md)
+ [Managing global clusters](global-clusters.manage.md)
+ [Connecting global clusters](global-clusters-connect.md)
+ [Monitoring global clusters](global-clusters-monitor.md)
+ [Disaster recovery](global-clusters-disaster-recovery.md)

# Quick start guide: global clusters
<a name="global-clusters.get-started"></a>

**Topics**
+ [Configuration](#global-clusters.config)
+ [Creating a global cluster](#global-clusters-create)
+ [Adding a Region to a global cluster](#global-clusters.add-region)
+ [Using a snapshot](#global-clusters.snapshot)

## Configuration
<a name="global-clusters.config"></a>

Amazon DocumentDB global cluster spans at least two AWS Regions. The primary Region supports a cluster that has one primary (writer) instance and up to 15 replica instances, while a secondary Region runs a read-only cluster made up entirely of up to 16 replica instances. A global cluster can have up to five secondary Regions. The table lists the maximum clusters, instances, and replicas allowed in a global cluster.


| Description | Primary AWS Region | Secondary AWS Region | 
| --- | --- | --- | 
| Clusters | 1 | 5 (maximum) | 
| Writer instances | 1 | 0 | 
| Read-only instances (Amazon DocumentDB replicas), per cluster | 15 (max) | 16 (total) | 
| Read-only instances (max allowed, given actual number of secondary Regions) | 15 - s | s = total number of secondary AWS Regions | 

The clusters have the following specific requirements:
+ **Database instance class requirements** — You can only use the `db.r5` and `db.r6g` instance classes. 
+ **AWS Region requirements** — The primary cluster must be in one Region, and at least one secondary cluster must be in a different Region of the same account. You can create up to five secondary (read-only) clusters, and each must be in a different Region. In other words, no two clusters can be in the same Region.
+ **Naming requirements** — The names you choose for each of your clusters must be unique, across all Regions. You can't use the same name for different clusters even though they're in different Regions.

## Creating an Amazon DocumentDB global cluster
<a name="global-clusters-create"></a>

Are you ready to build your first global cluster? In this section we will explain how to create a brand new global cluster with new database clusters and instances, using either the AWS Management Console or AWS CLI with the following instructions. 

### Using the AWS Management Console
<a name="global-clusters-create-console"></a>

1. In the AWS Management Console, navigate to **Amazon DocumentDB**.

1. When you get to the Amazon DocumentDB console, choose **Clusters**.  
![\[The Clusters page in the Amazon DocumentDB console.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/choose-cluster.png)

1. Choose **Create**.  
![\[The Create button shown in the upper-right corner of the Clusters table.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/choose-create.png)

1. Fill out the **Configuration** section of the **Create Amazon DocumentDB Cluster** form accordingly:
   + **Cluster identifier**: You can either enter a unique identifier for this instance or allow Amazon DocumentDB to provide the instance identifier based on the cluster identifier.
   + Engine version: Choose **4.0.0**
   + Instance class: Choose **db.r5.large**
   + Number of instances: Choose **3**.  
![\[Configuration options form for creating an Amazon DocumentDB cluster.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/create-config.png)

1. In the **Authentication** section, fill in a master username and master password.  
![\[Authentication form to specify a master username and password for a new Amazon DocumentDB cluster.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/create-auth.png)

1. Choose **Show advanced settings**.  
![\[Show advanced settings toggle button next to Cancel and Create cluster buttons.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/show-advanced.png)

1. In the **Network settings** section:
   + Keep default options for **Virtual Private Cloud (VPC)** and **Subnet group**.  
![\[Network settings form showing VPC, subnet group, and VPC security groups options. VPC and Subnet group fields have default options selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/default-vpc-1.png)
   + For **VPC security groups**, **default (VPC)** should already be added.  
![\[Network settings form showing default VPC already added.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/default-vpc-2.png)
   + Type `DocDB` into the **VPC security groups** field and select **DocDB-Inbound (VFC)**.  
![\[DocDB-Inbound VFC selected in VPC security groups dropdown menu.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/inbound-vfc.png)

1. For **Cluster options** and **Encryption-at-rest**, leave at default selections.  
![\[Cluster options and Encryption-at-rest forms with default options selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/leave-default-1.png)

1. For **Backup** and **Log exports**, leave at default selections.  
![\[Backup and Log exports forms with default options selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/leave-default-2.png)

1. For **Maintenance**, **Tags**, and **Deletion protection**, leave at default selections.  
![\[Maintenance, Tags, and Deletion protection forms with default options selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/leave-default-3.png)

1. Now click the button that says **Create cluster**.  
![\[The Create cluster button shown at the end of the cluster creation process.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/create-cluster.png)

### Using the AWS CLI
<a name="global-clusters-create-cli"></a>

To create an Amazon DocumentDB Regional cluster, call the [create-global-cluster AWS CLI](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/create-global-cluster.html). The following AWS CLI command creates an Amazon DocumentDB cluster named `global-cluster-id`. For more information on deletion protection, see [Deleting an Amazon DocumentDB cluster](db-cluster-delete.md). 

Also, `--engine-version` is an optional parameter that defaults to the latest major engine version. The current default engine version is `5.0.0` (note: Amazon DocumentDB 8.0 is available but must be explicitly specified as `8.0.0`). When new major engine versions are released, the default engine version for `--engine-version` will be updated to reflect the last major engine version. As a result, for production workloads, and especially those that are dependent on scripting, automation, or CloudFormation templates, we recommend that you explicitly specify the `--engine-version` to the intended major version.

If a `db-subnet-group-name` or `vpc-security-group-id` is not specified, Amazon DocumentDB will use the default subnet group and Amazon VPC security group for the given Region.

In the following example, replace each *user input placeholder* with your own information.

For Linux, macOS, or Unix:

```
aws docdb create-db-cluster \
      --global-cluster-identifier global-cluster-id \
      --source-db-cluster-identifier arn:aws:rds:us-east-1:111122223333:cluster-id
```

For Windows:

```
aws docdb create-db-cluster ^
      --global-cluster-identifier global-cluster-id ^
      --source-db-cluster-identifier arn:aws:rds:us-east-1:111122223333:cluster-id
```

Output from this operation looks something like the following (JSON format).

```
{
    "DBCluster": {
        "StorageEncrypted": false,
        "DBClusterMembers": [],
        "Engine": "docdb",
        "DeletionProtection" : "enabled",
        "ClusterCreateTime": "2018-11-26T17:15:19.885Z",
        "DBSubnetGroup": "default",
        "EngineVersion": "4.0.0",
        "MasterUsername": "masteruser",
        "BackupRetentionPeriod": 1,
        "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:cluster-id",
        "DBClusterIdentifier": "cluster-id",
        "MultiAZ": false,
        "DBClusterParameterGroup": "default.docdb4.0",
        "PreferredBackupWindow": "09:12-09:42",
        "DbClusterResourceId": "cluster-KQSGI4MHU4NTDDRVNLNTU7XVAY",
        "PreferredMaintenanceWindow": "tue:04:17-tue:04:47",
        "Port": 27017,
        "Status": "creating",
        "ReaderEndpoint": "cluster-id.cluster-ro-sfcrlcjcoroz.us-east-1.docdb.amazonaws.com",
        "AssociatedRoles": [],
        "HostedZoneId": "ZNKXTT8WH85VW",
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-77186e0d",
                "Status": "active"
            }
        ],
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1c",
            "us-east-1e"
        ],
        "Endpoint": "cluster-id.cluster-sfcrlcjcoroz.us-east-1.docdb.amazonaws.com"
    }
}
```

It takes several minutes to create the cluster. You can use the AWS Management Console or AWS CLI to monitor the status of your cluster. For more information, see [Monitoring an Amazon DocumentDB cluster's status](monitoring_docdb-cluster_status.md). 

**Important**  
When you use the AWS CLI to create an Amazon DocumentDB Regional cluster, no instances are created. Consequently, you must explicitly create a primary instance and any replica instances that you need. You can use either the console or AWS CLI to create the instances. For more information, see [Adding an Amazon DocumentDB instance to a cluster](db-instance-add.md) and [CreateDBCluster](API_CreateDBCluster.md) in the Amazon DocumentDB API Reference. 

Once your Regional cluster is available, you can add a secondary cluster in another Region with the following instructions: [Adding an AWS Region to an Amazon DocumentDB global cluster](#global-clusters.add-region). When you add a Region, your Regional cluster becomes your primary cluster, and you have a new secondary cluster in the Region you chose.

## Adding an AWS Region to an Amazon DocumentDB global cluster
<a name="global-clusters.add-region"></a>

A global cluster needs at least one secondary cluster in a different Region than the primary cluster, and you can add up to five secondary clusters. Note that for each secondary cluster that you add, you must reduce the number of replicas allowed in the primary cluster by one. For example, if your global cluster has five secondary Regions, your primary cluster can have only 10 (rather than 15) replicas. For more information, see [Configuration requirements of an Amazon DocumentDB global cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/global-clusters.get-started.html#global-clusters.config).

### Using the AWS Management Console
<a name="global-clusters-add-region-console"></a>

1. Sign in to the AWS Management Console and open the Amazon DocumentDB console.

1. In the navigation pane, choose **Clusters**.  
![\[The Clusters page in the Amazon DocumentDB console.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/choose-cluster.png)

1. Choose the cluster that you would like to add a secondary cluster to. Ensure that the cluster is `Available`.  
![\[List of regional and global clusters showing available status, with mydocdbglobalcluster highlighted.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/choose-cluster-2.png)

1. Select the dropdown list for **Actions** and then choose **Add Region**.  
![\[The Actions dropdown on the Clusters interface shows the Add Region option.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/add-region.png)

1. On the **Add an AWS Region** page, choose the secondary Region. Note that you can't choose a Region that already has a secondary cluster for the same global cluster. Also, it can't be the same Region as the primary cluster. If this is the first Region you are adding, you will also have to specify a global cluster identifier of your choice.  
![\[Choose a secondary region using the dropdown menu on the Add an AWS Region form.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/add-region-2.png)

1. Complete the remaining fields for the secondary cluster in the new Region, then select **Create cluster**. After you finish adding the Region, you can see it in the list of **Clusters** in the AWS Management Console.  
![\[Final steps of adding a region to a cluster, showing the Configuration form, hourly cost estimate, and Create cluster button.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/quick-start/select-add-region.png)

### Using the AWS CLI
<a name="global-clusters-add-region-cli"></a>
+ Use the `create-db-cluster` CLI command with the name `(--global-cluster-identifier)` of your global cluster. For other parameters, do the following:
  + For `--region`, choose a different AWS Region than that of your primary Region.
  + Choose specific values for the `--engine` and `--engine-version` parameters. 
  + For an encrypted cluster, specify your primary AWS Region as the `--source-region` for encryption.

The following example creates a new Amazon DocumentDB cluster and attaches it to the global cluster as a read-only secondary cluster. In the last step, the instance is added to the new cluster.

In the following example, replace each *user input placeholder* with your own information.

For Linux, macOS, or Unix:

```
aws docdb --region secondary-region-id \
  create-db-cluster \
    --db-cluster-identifier cluster-id \
    --global-cluster-identifier global-cluster-id \
    --engine-version version \
    --engine docdb

aws docdb --region secondary-region-id \
  create-db-instance \
    --db-cluster-identifier cluster-id \
    --global-cluster-identifier global-cluster-id \
    --engine-version version \
    --engine docdb
```

For Windows:

```
aws docdb --region secondary-region-id ^
  create-db-cluster ^
    --db-cluster-identifier cluster-id ^
    --global-cluster-identifier global-cluster-id ^
    --engine-version version ^
    --engine docdb

aws docdb --region secondary-region-id ^
  create-db-instance ^
    --db-cluster-identifier cluster-id ^
    --global-cluster-identifier global-cluster-id ^
    --engine-version version ^
    --engine docdb
```

## Using a snapshot for your Amazon DocumentDB global cluster
<a name="global-clusters.snapshot"></a>

You can restore a snapshot of an Amazon DocumentDB cluster to use as the starting point for your global cluster. To do this, you must restore the snapshot and create a new cluster. This will serve as the primary cluster of your global cluster. You can then add another Region to the restored cluster, thus converting it into a global cluster. 

# Managing an Amazon DocumentDB global cluster
<a name="global-clusters.manage"></a>

You perform most management operations on the individual clusters that make up a global cluster. When you choose **Group related resources** on the **Clusters** page in the console, you see the primary cluster and secondary clusters grouped under the associated global cluster.

The **Configuration** tab for a global cluster shows the AWS Regions where the clusters are running, the version, and the global cluster identifier.

**Topics**
+ [Modifying global clusters](#global-clusters.modify)
+ [Modifying parameters](#global-clusters.modify-parameters)
+ [Removing global clusters](#global-clusters.remove)
+ [Deleting global clusters](#global-clusters.delete)
+ [Headless clusters](#global-clusters.headless)

## Modifying an Amazon DocumentDB global cluster
<a name="global-clusters.modify"></a>

The **Clusters** page in the AWS Management Console lists all your global clusters, showing the primary cluster and secondary clusters for each one. The global cluster has its own configuration settings. Specifically, it has regions associated with its primary and secondary clusters.

When you make changes to the global cluster, you have a chance to cancel changes.

When you choose Continue, you confirm the changes.

## Modifying parameters an Amazon DocumentDB global cluster
<a name="global-clusters.modify-parameters"></a>

You can configure the cluster parameter groups independently for each cluster within the global cluster. Most parameters work the same as for other kinds of Amazon DocumentDB clusters. We recommend that you keep settings consistent among all the clusters in a global database. Doing this helps to avoid unexpected behavior changes if you promote a secondary cluster to be the primary.

For example, use the same settings for time zones and character sets to avoid inconsistent behavior if a different cluster takes over as the primary cluster.

## Removing a cluster from an Amazon DocumentDB global cluster
<a name="global-clusters.remove"></a>

There are several situations when you may want to remove clusters from your global cluster. For example, you might want to remove a cluster from a global cluster if the primary cluster becomes degraded or isolated. It then becomes a standalone provisioned cluster that could be used to create a new global cluster. To learn more, see [Performing a manual failover for an Amazon DocumentDB global cluster](global-clusters-disaster-recovery.md#manual-failover).

You also might want to remove clusters because you want to delete a global cluster that you no longer need. You can't delete the global cluster until after you detach all associated clusters, leaving the primary for last. For more information, see [Deleting a cluster from an Amazon DocumentDB global cluster](#global-clusters.delete).

**Note**  
When a cluster is detached from the global cluster, it's no longer synchronized with the primary. It becomes a standalone provisioned cluster with full read/write capabilities. Additionally, it is no longer visible in the Amazon DocumentDB console. It is only visible when you select the region in the console that the cluster was located in.

You can remove clusters from your global cluster using the AWS Management Console, the AWS CLI, or the RDS API.

------
#### [ Using the AWS Management Console ]

1. Sign in to the AWS Management Console and navigate to the Amazon DocumentDB console.

1. Choose **Clusters** on the left side navigation.  
![\[Image: the Clusters navigation box showing a list of existing cluster links and their corresponding instance links.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/choose-cluster.png)

1. Expand the global cluster so you can see all the secondary clusters. Select the secondary clusters you wish to remove. Choose **Actions**, and in the menu that drops down, choose **Remove from Global**.  
![\[Image: the Clusters navigation box showing the selection of an existing secondary cluster and highlighting the "Remove from global" action.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/remove-global.png)

1. A prompt will appear, asking you to confirm that you want to detach the secondary from the global cluster. Choose **Remove and promote** to remove the cluster from the global cluster.  
![\[Image: the Remove and promote prompt.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/remove-promote.png)

Now that cluster is no longer serving as a secondary and no longer synchronized with the primary cluster. It is a standalone cluster with full read/write capability.

After you remove or delete all secondary clusters, then you can remove the primary cluster the same way. You can't detach or remove the primary cluster from the global cluster until after you have removed all secondary clusters. The global cluster might remain in the Clusters list, with zero regions and AZs. You can delete if you no longer want to use this global cluster.

------
#### [ Using the AWS CLI ]

To remove a cluster from a global cluster, run the `remove-from-global-cluster` CLI command with the following parameters:
+ `--global-cluster-identifier` — The name (identifier) of your global cluster.
+ `--db-cluster-identifier` — The name of each cluster to remove from the global cluster. 

The following examples first remove a secondary cluster and then the primary cluster from a global cluster.

For Linux, macOS, or Unix:

```
aws docdb --region secondary_region \
  remove-from-global-cluster \
    --db-cluster-identifier secondary_cluster_ARN \
    --global-cluster-identifier global_cluster_id

aws docdb --region primary_region \
  remove-from-global-cluster \
    --db-cluster-identifier primary_cluster_ARN \
    --global-cluster-identifier global_cluster_id
```

Repeat the `remove-from-global-cluster` `--db-cluster-identifier` `secondary_cluster_ARN` command for each secondary region in your global cluster.

For Windows:

```
aws docdb --region secondary_region ^
  remove-from-global-cluster ^
    --db-cluster-identifier secondary_cluster_ARN ^
    --global-cluster-identifier global_cluster_id

aws docdb --region primary_region ^
  remove-from-global-cluster ^
    --db-cluster-identifier primary_cluster_ARN ^
    --global-cluster-identifier global_cluster_id
```

Repeat the `remove-from-global-cluster` `--db-cluster-identifier` `secondary_cluster_ARN` command for each secondary region in your global cluster.

------

## Deleting a cluster from an Amazon DocumentDB global cluster
<a name="global-clusters.delete"></a>

To delete a global cluster, do the following:
+ Remove all secondary clusters from the global cluster. Each cluster becomes a standalone cluster. See the previous section, [Removing a cluster from an Amazon DocumentDB global cluster](#global-clusters.remove).
+ From each standalone cluster, delete all replicas.
+ Remove the primary cluster from the global cluster. This becomes a standalone cluster.
+ From the primary cluster, first delete all replicas, then delete the primary instance. Deleting the primary instance from the newly standalone cluster also typically removes both the cluster and the global cluster.

------
#### [ Using the AWS Management Console ]

1. Sign in to the AWS Management Console and navigate to the Amazon DocumentDB console.

1. Choose **Clusters** and find the global cluster you want to delete.  
![\[Image: the Clusters navigation box showing a list of existing cluster links and their corresponding instance links.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/choose-cluster.png)

1. With your global cluster selected, choose **Delete** from the **Actions** menu.  
![\[Image: the Clusters navigation box showing the selection of a global cluster and highlighting the "Delete" action.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/global-clusters/delete-cluster.png)

Confirm that all clusters are removed from the global cluster. The global cluster should show zero regions and AZs and a size of zero clusters. If the global cluster contains any clusters, you can't delete it yet. You’ll first have to follow the instructions in the previous step, **[Removing a cluster from an Amazon DocumentDB global cluster](#global-clusters.remove)**.

------
#### [ Using the AWS CLI ]

To delete a global cluster, run the `delete-global-cluster` CLI command with the name of the AWS Region and the global cluster identifier, as shown in the following example.

For Linux, macOS, or Unix:

```
aws docdb --region primary_region delete-global-cluster \
   --global-cluster-identifier global_cluster_id
```

For Windows:

```
aws docdb --region primary_region delete-global-cluster ^
   --global-cluster-identifier global_cluster_id
```

------

## Creating a headless Amazon DocumentDB cluster in a secondary region
<a name="global-clusters.headless"></a>

Although an Amazon DocumentDB global cluster requires at least one secondary cluster in a different AWS Region than the primary, you can use a headless configuration for the secondary cluster. A headless secondary Amazon DocumentDB cluster is one without an instance. This type of configuration can lower expenses for a global cluster. In an Amazon DocumentDB cluster, compute and storage are decoupled. Without the instance, you're not charged for compute, only for storage. If it's set up correctly, a headless secondary's storage volume is kept in sync with the primary cluster. 

You add the secondary cluster as you normally do when creating an Amazon DocumentDB global cluster. However, after the primary cluster begins replication to the secondary, you delete the read-only instance from the secondary cluster. This secondary cluster is now considered "headless" because it no longer has a Instance. Yet, the storage volume is kept in sync with the primary Amazon DocumentDB cluster. 

**Important**  
We only recommend headless clusters for customers who can tolerate region-wide failures for 15\$1 minutes. This is because recovering from a region-wide failure with a headless secondary cluster will require the user to create a new instance after failing over. A new instance can take \$110-15 minutes to become available.

### How to Add a Headless Secondary Cluster to Your Global Cluster
<a name="w2aac35b9c13c17b9"></a>

1. Sign in to the AWS Management Console and open the [Amazon DocumentDB console](https://console.aws.amazon.com/rds/).

1. Choose **Clusters** on the left side navigation. 

1. Choose the global cluster that needs a secondary cluster. Ensure that the primary cluster is `Available`. 

1. For **Actions**, choose **Add region**.

1. On the **Add a region** page, choose the secondary region.
**Note**  
You can't choose a region that already has a secondary cluster for the same global cluster. Also, it can't be the same region as the primary cluster. 

1. Complete the remaining fields for the secondary cluster in the new region. These are the same configuration options as for any cluster instance. 

1. Add a region. After you finish adding the region to your global cluster, you will see it in the list of `Clusters` in the AWS Management Console. 

1. Check the status of the secondary cluster and its reader instance before continuing, by using the AWS Management Console or the AWS CLI. Here is a sample command if you use the AWS CLI: 

   ```
   $ aws docdb describe-db-clusters --db-cluster-identifier secondary-cluster-id --query '*[].[Status]' --output text
   ```

   It can take several minutes for the status of a newly added secondary cluster to change from creating to available. When the cluster is available, you can delete the reader instance. 

1. Select the reader instance in the secondary cluster, and then choose **Delete**. 

1. After deleting the reader instance, the secondary cluster remains part of the global cluster. It should have no instance associated with it.

**Note**  
You can use this headless secondary Amazon DocumentDB cluster to manually recover your Amazon DocumentDB global cluster from an unplanned outage in the primary region if such an outage occurs. 

# Connect to an Amazon DocumentDB global cluster
<a name="global-clusters-connect"></a>

How you connect to a global cluster depends on whether you need to write to the cluster or read from the cluster:
+ For read-only requests or queries, you connect to the reader endpoint for the cluster in your AWS Region.
+ To run data manipulation language (DML) or data definition language (DDL) statements, you connect to the cluster endpoint for the primary cluster. This endpoint might be in a different AWS Region than your application.

When you view a global cluster in the console, you can see all the general-purpose endpoints associated with all of its clusters.

How you connect to a global cluster depends on whether you need to write to the database or read from the database. For DDL, DML and read operations that you would like to serve from the primary region, you should connect to your primary cluster. We recommend that you connect to your primary cluster using the cluster endpoint in replica set mode, with a read preference of `secondaryPreferred=true`. This will route write traffic to your primary cluster’s writer instance and read traffic to your primary cluster’s replica instance.

For cross region, read only traffic, you should connect to one of your secondary clusters. We recommend that you connect to your secondary cluster using the cluster endpoint in replica set mode. Since all instances are read-only replica instances, you do not need to specify a read preference. To minimize latency, choose whichever reader endpoint is in your region or the region closest to you.

# Monitoring Amazon DocumentDB global clusters
<a name="global-clusters-monitor"></a>

Amazon DocumentDB (with MongoDB compatibility) integrates with CloudWatch so that you can gather and analyze operational metrics for your clusters. You can monitor these metrics using the CloudWatch console, the Amazon DocumentDB console, the AWS Command Line Interface (AWS CLI), or the CloudWatch API.

To monitor a global cluster, use the following CloudWatch metrics.


| Metric | Description | 
| --- | --- | 
| GlobalClusterReplicatedWriteIO | The average number of billed write I/O operations replicated from the cluster volume in the primary AWS Region to the cluster volume in a secondary AWS Region, reported at 5-minute intervals. The number of replicated ReplicatedWriteIOs to each secondary region is the same as the number of in-region VolumeWriteIOPs performed by the primary region. | 
| GlobalClusterDataTransferBytes | The amount of data transferred from the primary cluster’s AWS Region to a secondary cluster’s AWS Region, measure in bytes. | 
| GlobalClusterReplicationLag | The amount of lag, in milliseconds, when replicating change events from the primary cluster’s AWS Region to a secondary cluster’s AWS Region | 

For more information on how to view these metrics, please see [Viewing CloudWatch data](https://docs.aws.amazon.com/documentdb/latest/developerguide/cloud_watch.html#cloud_watch-view_data).

# Disaster recovery and Amazon DocumentDB global clusters
<a name="global-clusters-disaster-recovery"></a>

**Topics**
+ [

## Performing a managed failover for an Amazon DocumentDB global cluster
](#managed-failover)
+ [

## Performing a manual failover for an Amazon DocumentDB global cluster
](#manual-failover)
+ [

## Performing a switchover for an Amazon DocumentDB global cluster
](#global-cluster-switchover)
+ [

## Unblocking a global cluster switchover or failover
](#unblocking-gc-so-fo)

By using a global cluster, you can recover from disasters such as region failures quickly. Recovery from disaster is typically measured using values for RTO and RPO.
+ **Recovery time objective (RTO)** — The time it takes a system to return to a working state after a disaster. In other words, RTO measures downtime. For a global cluster, RTO in minutes.
+ **Recovery point objective (RPO)** — The amount of data that can be lost (measured in time). For a global cluster, RPO is typically measured in seconds. 
+ To recover from an unplanned outage, you can perform a cross-region failover to one of the secondaries in your global cluster. When your global cluster has multiple secondary regions, make sure that you detach all the secondary regions that you wish to promote as primaries. Then, you promote one of those secondary regions to be the new primary AWS Region. Finally, you create new clusters in each of the other secondary regions and attach those clusters to your global cluster.

## Performing a managed failover for an Amazon DocumentDB global cluster
<a name="managed-failover"></a>

This approach is intended for business continuity in the event of a true Regional disaster or complete service-level outage.

During a managed failover, your primary cluster is failed over to your choice of secondary Region while your Amazon DocumentDB global cluster's existing replication topology is maintained. The chosen secondary cluster promotes one of its read-only nodes to full writer status. This step allows the cluster to assume the role of primary cluster. Your database is unavailable for a short time while this cluster is assuming its new role. Data that wasn't replicated from the old primary to the chosen secondary cluster may be missing when this secondary becomes the new primary. The old primary volume makes a best effort attempt to take a snapshot before synchronizing with the new primary so unreplicated data is preserved on the snapshot.

**Note**  
You can only perform a managed cross-Region cluster failover on an Amazon DocumentDB global cluster if the primary and all secondary clusters have the same engine versions. If your engine versions are incompatible, you can perform the failover manually by following the steps in [Performing a manual failover for an Amazon DocumentDB global cluster](#manual-failover).  
If the region's engine versions do not match, the failover will be blocked. Please check for any pending upgrades and apply them to ensure all region's engine versions match and the global cluster failover is unblocked. For more information, see [Unblocking a global cluster switchover or failover](#unblocking-gc-so-fo).

To minimize data loss, we recommend that you do the following before using this feature:
+ Take applications offline to prevent writes from being sent to the primary cluster of the Amazon DocumentDB global cluster.
+ Check lag times for all Amazon DocumentDB secondary clusters. Choosing the secondary Region with the least replication lag can minimize data loss with the current failed primary Region. Check lag times for all Amazon DocumentDB secondary clusters in the global cluster by viewing the `GlobalClusterReplicationLag` metric in Amazon CloudWatch. These metrics show you how far behind (in milliseconds) replication to a secondary cluster is to the primary cluster.

  For more information about CloudWatch metrics for Amazon DocumentDB, see [Amazon DocumentDB metrics](cloud_watch.md#cloud_watch-metrics_list).

During a managed failover, the chosen secondary cluster is promoted to its new role as primary. However, it doesn't inherit the various configuration options of the primary cluster. A mismatch in configuration can lead to performance issues, workload incompatibilities, and other anomalous behavior. To avoid such issues, we recommend that you resolve differences between your Amazon DocumentDB global clusters for the following:
+ **Configure an Amazon DocumentDB cluster parameter group for the new primary, if necessary** — You can configure your Amazon DocumentDB cluster parameter groups independently for each cluster in your Amazon DocumentDB global clustere. Therefore, when you promote a secondary cluster to take over the primary role, the parameter group from the secondary might be configured differently than for the primary. If so, modify the promoted secondary cluster's parameter group to conform to your primary cluster's settings. To learn how, see [Modifying Amazon DocumentDB cluster parameter groups](cluster_parameter_groups-modify.md).
+ **Configure monitoring tools and options, such as Amazon CloudWatch events and alarms** — Configure the promoted cluster with the same logging ability, alarms, and so on as needed for the global cluster. As with parameter groups, configuration for these features isn't inherited from the primary during the failover process. Some CloudWatch metrics, such as replication lag, are only available for secondary Regions. Thus, a failover changes how to view those metrics and set alarms on them, and could require changes to any predefined dashboards. For more information about Amazon DocumentDB clusters and monitoring, see [Monitoring Amazon DocumentDB](monitoring_docdb.md).

Typically, the chosen secondary cluster assumes the primary role within a minute. As soon as the new primary Region's writer node is available, you can connect your applications to it and resume your workloads. After Amazon DocumentDB promotes the new primary cluster, it automatically rebuilds all additional secondary Region clusters.

Because Amazon DocumentDB global clusters use asynchronous replication, the replication lag in each secondary Region can vary. Amazon DocumentDB rebuilds these secondary Regions to have the exact same point-in-time data as the new primary Region cluster. The duration of the complete rebuilding task can take a few minutes to several hours, depending on the size of the storage volume and the distance between the Regions. When the secondary Region clusters finish rebuilding from the new primary Region, they become available for read access. As soon as the new primary writer is promoted and available, the new primary Region's cluster can handle read and write operations for the Amazon DocumentDB global cluster.

To restore the global cluster's original topology, Amazon DocumentDB monitors the availability of the old primary Region. As soon as that Region is healthy and available again, Amazon DocumentDB automatically adds it back to the global cluster as a secondary Region. Before creating the new storage volume in the old primary Region, Amazon DocumentDB tries to take a snapshot of the old storage volume at the point of failure. It does this so that you can use it to recover any of the missing data. If this operation is successful, Amazon DocumentDB places this snapshot named "rds:docdb-unplanned-global-failover-name-of-old-primary-DB-cluster-timestamp" in the snapshot section of the AWS Management Console. You can also see this snapshot listed in the information returned by the `DescribeDBClusterSnapshots` API operation.

**Note**  
The snapshot of the old storage volume is a system snapshot that's subject to the backup retention period configured on the old primary cluster. To preserve this snapshot outside of the retention period, you can copy it to save it as a manual snapshot. To learn more about copying snapshots, including pricing, see [Copying a cluster snapshot](backup_restore-copy_cluster_snapshot.md#backup_restore-copy_a_cluster_snapshot).

After the original topology is restored, you can fail back your global cluster to the original primary Region by performing a switchover operation when it makes the most sense for your business and workload. To do so, follow the steps in [Performing a switchover for an Amazon DocumentDB global cluster](#global-cluster-switchover).

You can fail over your Amazon DocumentDB global cluster using the AWS Management Console, the AWS CLI, or the Amazon DocumentDB API.

------
#### [ Using the AWS Management Console ]

**Perform a managed failover on your Amazon DocumentDB global cluster**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.

1. Find and choose the Amazon DocumentDB global cluster you want to fail over.  
![\[Image: Cluster table with global cluster selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/failover-cluster-table.png)

1. Choose **Switchover or Failover** from the **Actions** menu.

1. On the dialog box that appears, choose **Failover**, then choose the secondary cluster from the **New primary cluster** field drop down list.  
![\[Image: Global cluster switchover or failover dialog box.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/switch-fail-confirm.png)

1. Type "confirm" in the last field. Then choose **Confirm**.

   The status of the primary cluster changes to "**Failing-over**". This condition should take approximately one minute. During this time, the status of the new primary cluster shows "**Modifying...**". Once the new primary is promoted, it will show "**Available**" and will be able to serve read and write transactions. The secondary regions including the old primary will show "**Resyncing...**" while it resynchronizes to the new primary. Similar to the new primary, it will only be able to serve transaction once the status changes to "**Available**".

1. When complete, the original primary cluster becomes the secondary cluster. The selected secondary cluster becomes the primary cluster.  
![\[Image: Cluster table showing new primary cluster.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/failover-complete.png)

------
#### [ Using the AWS CLI ]

**Perform a managed failover on your Amazon DocumentDB global cluster**

Run the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/failover-global-cluster.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/failover-global-cluster.html) CLI command to fail over your Amazon DocumentDB global cluster. With the command, pass values for the following options:
+ `--region`
+ `--global-cluster-identifier`
+ `--target-db-cluster-identifier`
+ `--allow-data-loss`

In the following examples, replace each *user input placeholder* with your cluster's information.

For Linux, macOS, or Unix:

```
aws docdb failover-global-cluster \
   --region region_of_selected_secondary \
   --global-cluster-identifier global_cluster_id \
   --target-db-cluster-identifier arn_of_secondary_to_promote \
   --allow-data-loss
```

For Windows:

```
aws docdb failover-global-cluster ^
   --region region_of_selected_secondary ^
   --global-cluster-identifier global_cluster_id ^
   --target-db-cluster-identifier arn_of_secondary_to_promote ^
   --allow-data-loss
```

------

## Performing a manual failover for an Amazon DocumentDB global cluster
<a name="manual-failover"></a>

If an entire cluster in one AWS Region becomes unavailable, you can promote another cluster in the global cluster to have read/write capability.

You can manually activate the global cluster failover mechanism if a cluster in a different AWS Region is a better choice to be the primary cluster. For example, you might increase the capacity of one of the secondary clusters and then promote it to be the primary cluster. Or the balance of activity among the AWS Regions might change, so that switching the primary cluster to a different AWS Region might give lower latency for write operations.

The following procedure outlines what to do to promote one of the secondary clusters in an Amazon DocumentDB global cluster.

To promote a secondary cluster:

1. Stop issuing DML statements and other write operations to the primary cluster in the AWS Region with the outage.

1. Identify a cluster from a secondary AWS Region to use as a new primary cluster. If you have two (or more) secondary AWS Regions in your global cluster, choose the secondary cluster that has the least lag time.

1. Detach your chosen secondary cluster from the global cluster.

   Removing a secondary cluster from a global cluster immediately stops the replication from the primary to this secondary and promotes it to standalone provisioned cluster with full read/write capabilities. Any other secondary cluster associated with the primary cluster in the region with the outage are still available and can accept calls from your application. They also consume resources. Since you are recreating the global cluster, to avoid split-brain and other issues, remove the other secondary clusters before creating the new global cluster in the steps that follow.

   For detailed steps for detaching, see [Removing a cluster from an Amazon DocumentDB global cluster](global-clusters.manage.md#global-clusters.remove).

1. This cluster becomes the primary cluster of a new global cluster when you start adding Regions to it, in the next step.

1. Add an AWS Region to the cluster. When you do this, the replication process from primary to secondary begins.

1. Add more AWS Regions as needed to re-create the topology needed to support your application. Make sure that application writes are sent to the correct cluster before, during, and after making changes such as these, to avoid data inconsistencies among the clusters in the global cluster (split-brain issues).

1. When the outage is resolved and you're ready to assign your original AWS Region as the primary cluster again, perform the same steps in reverse.

1. Remove one of the secondary clusters from the global cluster. This will enable it to serve read/write traffic. 

1. Redirect all the write traffic to the primary cluster in the original AWS Region.

1. Add an AWS Region to set up one or more secondary clusters in the same AWS Region as before.

Amazon DocumentDB global clusters can be managed using AWS SDKs, enabling you to create solutions to automate global cluster failover process for Disaster Recovery and Business Continuity Planning use cases. One such solution is made available for our customers under Apache 2.0 licensing and can be accessed from our tools repository [here](https://github.com/awslabs/amazon-documentdb-tools/tree/master/global-clusters-automation). This solution leverages Amazon Route 53 for endpoint management and provides AWS Lambda functions that can be triggered based appropriate events.

## Performing a switchover for an Amazon DocumentDB global cluster
<a name="global-cluster-switchover"></a>

By using switchovers, you can change the Region of your primary cluster on a routine basis. This approach is intended for controlled scenarios, such as operational maintenance and other planned operational procedures.

There are three common use cases for using switchovers:
+ For "regional rotation" requirements imposed on specific industries. For example, financial service regulations might want tier-0 systems to switch to a different Region for several months to ensure that disaster recovery procedures are regularly exercised.
+ For multi-Region "follow-the-sun" applications. For example, a business might want to provide lower latency writes in different Regions based on business hours across different time zones.
+ As a zero-data-loss method to fail back to the original primary Region after a failover.

**Note**  
Switchovers are designed to be used on a healthy Amazon DocumentDB global cluster. To recover from an unplanned outage, follow the appropriate procedure in [Performing a manual failover for an Amazon DocumentDB global cluster](#manual-failover).  
To perform a switchover, all secondary regions must be running the exact same engine version as the primary. If the region's engine versions do not match, the switchover will be blocked. Please check for any pending upgrades and apply them to ensure all region's engine versions match and the global cluster switchover is unblocked. For more information, see [Unblocking a global cluster switchover or failover](#unblocking-gc-so-fo).

During a switchover, Amazon DocumentDB switches over your primary cluster to your chosen secondary Region while it maintains your global cluster's existing replication topology. Before it starts the switchover process, Amazon DocumentDB waits for all secondary Region clusters to be fully synchronized with the primary Region cluster. Then, the DB cluster in the primary Region becomes read-only and the chosen secondary cluster promotes one of its read-only nodes to full writer status. Promoting this node to a writer allows that secondary cluster to assume the role of primary cluster. Because all secondary clusters were synchronized with the primary at the beginning of the process, the new primary continues operations for the Amazon DocumentDB global cluster without losing any data. Your database is unavailable for a short time while the primary and selected secondary clusters are assuming their new roles.

To optimize application availability, we recommend that you do the following before using this feature:
+ Perform this operation during nonpeak hours or at another time when writes to the primary cluster are minimal.
+ Take applications offline to prevent writes from being sent to the primary cluster of the Amazon DocumentDB global cluster.
+ Check lag times for all Amazon DocumentDB secondary clusters in the global cluster by viewing the `GlobalClusterReplicationLag` metric in Amazon CloudWatch. This metric shows you how far behind (in milliseconds) replication to a secondary cluster is to the primary cluster. This value is directly proportional to the time it takes for Amazon DocumentDB to complete the switchover. Therefore, the larger the lag value, the longer the switchover will take.

  For more information about CloudWatch metrics for Amazon DocumentDB, see [Amazon DocumentDB metrics](cloud_watch.md#cloud_watch-metrics_list).

During a switchover, the chosen secondary DB cluster is promoted to its new role as primary. However, it doesn't inherit the various configuration options of the primary DB cluster. A mismatch in configuration can lead to performance issues, workload incompatibilities, and other anomalous behavior. To avoid such issues, we recommend that you resolve differences between your Amazon DocumentDB global clusters for the following:
+ **Configure Amazon DocumentDB DB cluster parameter group for the new primary, if necessary** — You can configure your Amazon DocumentDB cluster parameter groups independently for each cluster in your Amazon DocumentDB global cluster. That means that when you promote a secondary DB cluster to take over the primary role, the parameter group from the secondary might be configured differently than for the primary. If so, modify the promoted secondary DB cluster's parameter group to conform to your primary cluster's settings. To learn how, see [Managing Amazon DocumentDB cluster parameter groups](cluster_parameter_groups.md).
+ **Configure monitoring tools and options, such as Amazon CloudWatch Events and alarms** — Configure the promoted cluster with the same logging ability, alarms, and so on as needed for the global cluster. As with parameter groups, configuration for these features isn't inherited from the primary during the switchover process. Some CloudWatch metrics, such as replication lag, are only available for primary Regions. Thus, a switchover changes how to view those metrics and set alarms on them, and could require changes to any predefined dashboards. For more information, see [Monitoring Amazon DocumentDB](monitoring_docdb.md).

**Note**  
Typically, the role switchover can take up to several minutes.

When the switchover process completes, the promoted Amazon DocumentDB cluster can handle write operations for the global cluster.

You can switch over your Amazon DocumentDB global cluster using the AWS Management Console or the AWS CLI:

------
#### [ Using the AWS Management Console ]

**Perform a switchover on your Amazon DocumentDB global cluster**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.

1. Find and select the Amazon DocumentDB global cluster you want to switch over.  
![\[Image: Cluster table with global cluster selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/switchover-cluster-table.png)

1. Choose **Switchover or Failover** from the **Actions **menu.

1. On the dialog box that appears, choose **Switchover**, then choose the secondary cluster from the **New primary cluster** field drop down list.  
![\[Image: Cluster switch over dialog with secondary cluster selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/switch-fail-confirm-2.png)

1. Choose **Confirm**.

   The status of the primary cluster changes to "**Switching-over**". This condition should take approximately three minutes. During this time, the status of all regional clusters show "**Modifying...**". Once the regions are synchronized and the new primary is promoted, it will show "**Available**" for all status fields and will be able to serve transactions.

1. When complete, the original primary cluster becomes the secondary cluster. The selected secondary cluster becomes the primary cluster.  
![\[Image: Cluster table showing new primary cluster.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/failover-complete.png)

------
#### [ Using the AWS CLI ]

**Perform a switchover on your Amazon DocumentDB global cluster**

Run the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/switchover-global-cluster.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/switchover-global-cluster.html) CLI command to switch over your Amazon DocumentDB global cluster. With the command, pass values for the following options:
+ `--region`
+ `--global-cluster-identifier`
+ `--target-db-cluster-identifier`

In the following examples, replace each *user input placeholder* with your cluster's information.

For Linux, macOS, or Unix:

```
aws docdb switchover-global-cluster \
   --region region_of_primary \
   --global-cluster-identifier global_cluster_id \
   --target-db-cluster-identifier arn_of_secondary_to_promote
```

For Windows:

```
aws docdb switchover-global-cluster ^
   --region region_of_primary ^
   --global-cluster-identifier global_cluster_id ^
   --target-db-cluster-identifier arn_of_secondary_to_promote
```

------

## Unblocking a global cluster switchover or failover
<a name="unblocking-gc-so-fo"></a>

Global cluster switchovers and failovers are blocked when not all regional clusters in the global cluster are on the same engine version. If the versions do not match, you may see this error in response when calling a switchover or failover: The target DB cluster specified is running an engine version with a different patch level than the source DB cluster. We recommended routinely applying the latest engine versions to ensure you are running the latest updates to keep your global clusters in a healthy state.

To resolve this error, please update all secondary regions first, and then the primary region to the same engine version by applying any pending maintenance action items. To view pending maintenance action items, and to apply any needed changes to correct the issue, perform the instructions in one of the following tabs:

------
#### [ Using the AWS Management Console ]

To unblock a global cluster switchover or failover, you must determine if there are any pending maintenance actions for your clusters and apply them. Follow these steps to view and apply maintenance actions:

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.

1. In the **Clusters** table, locate your global cluster in the **Cluster identifier** column. Under your global cluster, take note of each secondary cluster and the primary cluster for the given global cluster, and perform the following steps for each.

1. For each secondary cluster:

   1. If an update is available for your cluster, it is indicated as **Available**, **Required**, or **Next Window** in the **Maintenance** column.

   1. To take an action, choose the cluster to show it's details, then choose **Maintenance & backups**. The **Pending Maintenance** items appear.

   1. Under **Description**, if it indicates that a "New maintenance update is available", select it and then choose **Apply now**.

1. For your primary cluster:

   1. If an update is available for your cluster, it is indicated as **Available**, **Required**, or **Next Window** in the **Maintenance** column.

   1. To take an action, choose the cluster to show it's details, then choose **Maintenance & backups**. The **Pending Maintenance** items appear.

   1. Under **Description**, if it indicates that a "New maintenance update is available", select it and then choose **Apply now**.

------
#### [ Using the AWS CLI ]

To unblock a global cluster switchover or failover, you must determine if there are any pending maintenance actions for the cluster and apply them. Follow these steps to view and apply maintenance actions first on the secondary clusters then on the primary cluster for your global cluster:

1. Run the following on each secondary region's regional cluster first and then for the primary regions regional cluster.

1. Run the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-pending-maintenance-actions.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-pending-maintenance-actions.html) CLI command with the `--resource-identifier` option to determine if any maintenance actions are available for your Amazon DocumentDB regional cluster.

   In the following examples, replace each *user input placeholder* with your cluster's information.

   For Linux, macOS, or Unix:

   ```
   aws docdb describe-pending-maintenance-action \
      --resource-identifier arn:aws:rds:us-east-1:001234567890:cluster:docdb-2025-03-27-19-21-15
   ```

   For Windows:

   ```
   aws docdb describe-pending-maintenance-action ^
      --resource-identifier arn:aws:rds:us-east-1:001234567890:cluster:docdb-2025-03-27-19-21-15
   ```

   The result looks similar to this:

   ```
   {
       "PendingMaintenanceActions": [
           {
               "ResourceIdentifier": "arn:aws:rds:us-east-1:001234567890:cluster:docdb-2025-03-27-19-21-15",
               "PendingMaintenanceActionDetails": [
                   {
                       "Action": "system-update",
                       "CurrentApplyDate": "2025-04-11T03:01:00Z",
                       "Description": "db-version-upgrade",
                       "ForcedApplyDate": "2025-06-18T03:01:00Z",
                       "AutoAppliedAfterDate": "2025-05-11T03:01:00Z"
                       "OptInStatus": "pending"
                   }
               ]
           }
       ]
   }
   ```

1. If a maintenance action is needed, run the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/apply-pending-maintenance-action.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/apply-pending-maintenance-action.html) CLI command with the following options:
   + `--resource-identifier`
   + `--apply-action`
   + `--opt-in-type`
   + `--region`

   In the following examples, replace each *user input placeholder* with your cluster's information.

   For Linux, macOS, or Unix:

   ```
   aws docdb apply-pending-maintenance-action \
      --resource-identifier arn:aws:rds:us-east-1:001234567890:cluster:docdb-2025-03-27-19-21-15 \
      --apply-action system-update \
      --opt-in-type immediate \
      --region us-east-1
   ```

   For Windows:

   ```
   aws docdb apply-pending-maintenance-action ^
      --resource-identifier arn:aws:rds:us-east-1:001234567890:cluster:docdb-2025-03-27-19-21-15 ^
      --apply-action system-update ^
      --opt-in-type immediate ^
      --region us-east-1
   ```

1. Once the maintenance action has completed, run the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-pending-maintenance-actions.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-pending-maintenance-actions.html) command again to ensure that there are no other actions pending for your cluster.

   The result you want is:

   ```
   {
       "PendingMaintenanceActions": []
   }
   ```

------
#### [ Using the Amazon DocumentDB API ]

To unblock a global cluster switchover or failover, you must determine if there are any pending maintenance actions for the cluster and apply them. Use the following APIs to view and apply maintenance actions:

1. Run the following on each secondary region's regional cluster first and then for the primary regions regional cluster.

1. Call the [https://docs.aws.amazon.com/documentdb/latest/developerguide/API_PendingMaintenanceAction.html](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_PendingMaintenanceAction.html) API to determine if any maintenance actions are available for your Amazon DocumentDB global cluster.

1. Apply any changes by calling the [https://docs.aws.amazon.com/documentdb/latest/developerguide/API_ApplyPendingMaintenanceAction.html](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_ApplyPendingMaintenanceAction.html) API.

------

# Managing Amazon DocumentDB clusters
<a name="db-clusters"></a>

To manage an Amazon DocumentDB cluster, you must have an IAM policy with the appropriate Amazon DocumentDB control plane permissions. These permissions allow you to create, modify, and delete clusters and instances. The `AmazonDocDBFullAccess` policy provides all the required permissions for administering an Amazon DocumentDB cluster. 

The following topics show how to perform various tasks when working with Amazon DocumentDB clusters, including creating, deleting, modifying, connecting to, and viewing clusters.

**Topics**
+ [

# Understanding clusters
](db-clusters-understanding.md)
+ [Cluster settings](db-cluster-parameters.md)
+ [Cluster storage configurations](db-cluster-storage-configs.md)
+ [

# Determining a cluster's status
](db-cluster-status.md)
+ [Cluster lifecycle](db-cluster-life-cycle.md)
+ [Scaling clusters](db-cluster-manage-performance.md)
+ [Cloning a volume for a cluster](db-cluster-cloning.md)
+ [Understanding cluster fault tolerance](db-cluster-fault-tolerance.md)

# Understanding clusters
<a name="db-clusters-understanding"></a>

Amazon DocumentDB separates compute and storage, and offloads data replication and backup to the cluster volume. A cluster volume provides a durable, reliable, and highly available storage layer that replicates data six ways across three Availability Zones. Replicas enable higher data availability and read scaling. Each cluster can scale up to 15 replicas.


| Noun | Description | API Operations (Verbs) | 
| --- | --- | --- | 
|  Cluster  |  Consists of one or more instances and a cluster storage volume that manages the data for those instances.  |  `create-db-cluster` `delete-db-cluster` `describe-db-clusters` `modify-db-cluster` | 
| Instance | Reading and writing data to the cluster storage volume is done via instances. In a given cluster, there are two types of instances: primary and replica. A cluster always has one primary instance and can have 0–15 replicas. |  `create-db-instance` `delete-db-instance` `describe-db-instances` `modify-db-instance` `describe-orderable-db-instance-options` `reboot-db-instance` | 
| Cluster volume | A virtual database storage volume that spans three Availability Zones, with each Availability Zone having two copies of the cluster data. | N/A | 
|  Primary instance  |  Supports both read and write operations, and performs all data modifications to the cluster volume. Each cluster has one primary instance.  | N/A | 
|  Replica instance  |  Supports only read operations. Each Amazon DocumentDB cluster can have up to 15 replica instances in addition to the primary instance. Multiple replicas distribute the read workload. By locating replicas in separate Availability Zones, you can also increase database availability.  | N/A | 
|  Cluster endpoint  |  An endpoint for an Amazon DocumentDB cluster that connects to the current primary instance for the cluster. Each Amazon DocumentDB cluster has a cluster endpoint and one primary instance.  | N/A | 
|  Reader endpoint  |  An endpoint for an Amazon DocumentDB cluster that connects to one of the available replicas for that cluster. Each Amazon DocumentDB cluster has a reader endpoint. If there is more than one replica, the reader endpoint directs each connection request to one of the Amazon DocumentDB replicas.  | N/A | 
|  Instance endpoint  |  An endpoint for an instance in an Amazon DocumentDB cluster that connects to a specific instance. Each instance in a cluster, regardless of instance type, has its own unique instance endpoint.  | N/A | 

# Amazon DocumentDB Cluster settings
<a name="db-cluster-parameters"></a>

When you create or modify a cluster, it is important to understand which parameters are immutable and which are modifiable after the cluster has been created. The following table lists all the settings, or parameters, that are specific to a cluster. As specified in the table, some are modifiable, others are not.

**Note**  
These settings should not be confused with Amazon DocumentDB cluster parameter groups and their parameters. For more information about cluster parameter groups, see [Managing Amazon DocumentDB cluster parameter groups](cluster_parameter_groups.md). 


| Parameter | Modifiable | Notes | 
| --- | --- | --- | 
| DBClusterIdentifier | Yes |  Naming constraints: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameters.html)  | 
| Engine | No | Must be docdb. | 
| BackupRetentionPeriod | Yes | Must be between [1-35] days. | 
| DBClusterParameterGroupName | Yes |  Naming constraints: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameters.html)  | 
| DBSubnetGroupName | No | After a cluster has been created, you cannot modify the cluster's subnet. | 
| EngineVersion | No | Value can be 5.0.0 (default), 4.0.0, or 3.6.0. | 
| KmsKeyId | No | If you choose to encrypt your cluster, you cannot change the AWS KMS key that you used to encrypt your cluster. | 
| MasterUsername | No |  After a cluster has been created, you cannot modify the `MasterUsername`. Naming constraints: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameters.html)  | 
| MasterUserPassword | Yes |  Constraints: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameters.html)  | 
| Port | Yes | The port number applies to all instances in the cluster. | 
| PreferredBackupWindow | Yes |  | 
| PreferredMaintenanceWindow | Yes |  | 
| StorageEncrypted | No | If you choose to encrypt your cluster, it cannot be unencrypted. | 
| StorageType | Yes |  The storage type for the DB cluster: Standard (`standard`) or I/O-Optimized (`iopt1`). Default: `standard` This parameter can be configured with `CreateDBCluster` and `ModifyDBCluster`. For more information, see [Amazon DocumentDB cluster storage configurations](db-cluster-storage-configs.md).  | 
| Tags | Yes |  | 
| VpcSecurityGroupIds | No | After a cluster has been created, you cannot modify the VPC that the cluster resides in. | 

# Amazon DocumentDB cluster storage configurations
<a name="db-cluster-storage-configs"></a>

Starting from Amazon DocumentDB 5.0, instance-based clusters support two storage configuration types:
+ **Amazon DocumentDB standard storage**: Designed for customers with low to moderate I/O consumption. If you expect your I/O costs to be less than 25% of your total Amazon DocumentDB cluster, this choice might be ideal for you. With the Amazon DocumentDB standard storage configuration, you’re billed on a pay-per-request I/O basis in addition to instance and storage charges. This means your billing might vary from one cycle to another based on usage. The configuration is tailored to accommodate fluctuating I/O demands of your application.
+ **Amazon DocumentDB I/O-optimized storage**: Designed for customers who prioritize price predictability or have I/O intensive applications. The I/O-optimized configuration offers improved performance, increased throughput, and reduced latency for customers with I/O intensive workloads. If you expect your I/O costs to exceed 25% of your total Amazon DocumentDB cluster costs, this option offers enhanced price performance. With the Amazon DocumentDB I/O-optimized storage configuration, you won't be charged based on I/O operations, ensuring predictable costs each billing cycle. The configuration stabilizes costs while improving performance.

You can switch your existing database clusters once every 30 days to Amazon DocumentDB I/O-optimized storage. You can switch back to Amazon DocumentDB standard storage at any time. The next date to modify the storage configuration to I/O-optimized can be tracked with the `describe-db-clusters` command using the AWS CLI or through the AWS Management Console in the cluster's configuration page.

You can create a new database cluster including the Amazon DocumentDB I/O-optimized configuration or convert your existing database clusters with a few clicks in the [AWS Management Console](https://console.aws.amazon.com/docdb/), a single parameter change in the [AWS Command Line Interface (AWS CLI)](https://aws.amazon.com/cli/), or through [AWS SDKs](https://aws.amazon.com/developer/tools/). There is no downtime or reboot of instances required during or after modifying the storage configuration.

![\[Image: A table describing the differences between Amazon DocumentDB standard and optimized storage.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/io-diagram-1.png)


## Creating an I/O-optimized cluster
<a name="w2aac35c11c13c15"></a>



------
#### [ Using the AWS Management Console ]

To create or modify an I/O-optimized cluster using the AWS Management Console:

1. On the Amazon DocumentDB management console, under **Clusters**, choose either **Create** or select the cluster and choose **Actions**, and then choose **Modify**.

1. If you are creating a new cluster, make sure you choose **Instance Based Cluster** in the **Cluster type** section (this is the default option).  
![\[Image: A console screen capture of the cluster type options.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/create-cluster/cc-type.png)

1. In the **Configuration** section, under **Cluster storage configuration**, choose **Amazon DocumentDB I/O-Optimized**.  
![\[Image: A console screen capture of the cluster storage configuration options.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/storage-config-1.png)

1. Complete your cluster creation or modification and choose **Create cluster** or **Modify cluster**.

   For the complete Create cluster process, see [Creating a cluster and primary instance using the AWS Management Console](db-cluster-create.md#db-cluster-create-con).

   For the complete Modify cluster process, see [Modifying an Amazon DocumentDB cluster](db-cluster-modify.md).

------
#### [ Using the AWS CLI ]

To create an I/O-optimized cluster using the AWS CLI:

In the following examples, replace each *user input placeholder* with your own information.

For Linux, macOS, or Unix:

```
aws docdb create-db-cluster \
      --db-cluster-identifier sample-cluster \
      --engine docdb \
      --engine-version 5.0.0 \
      --storage-type iopt1 \
      --deletion-protection \
      --master-username username \
      --master-user-password password
```

For Windows:

```
aws docdb create-db-cluster ^
      --db-cluster-identifier sample-cluster ^
      --engine docdb ^
      --engine-version 5.0.0 ^
      --storage-type iopt1 ^
      --deletion-protection ^
      --master-username username ^
      --master-user-password password
```

------

## Cost analysis for determining storage configuration
<a name="w2aac35c11c13c17"></a>

With Amazon DocumentDB, you have the flexibility to choose your storage configuration for every database cluster you have. In order to properly allocate your clusters between standard and I/O-optimized, you can track your Amazon DocumentDB costs cluster-wise. To do so, you can add tags to existing clusters, enable cost allocation tagging in your [AWS Billing and Cost Management dashboard](https://aws.amazon.com/pricing/), and analyze your costs for a given cluster in the [AWS Cost Explorer Service](https://aws.amazon.com/aws-cost-management/aws-cost-explorer/). For information on cost analysis, see our blog [Using cost allocation tags](https://aws.amazon.com/blogs/database/using-cost-allocation-tags-with-amazon-documentdb-with-mongodb-compatibility/).

# Determining a cluster's status
<a name="db-cluster-status"></a>

You can determine a cluster's status using the AWS Management Console or AWS CLI.

------
#### [ Using the AWS Management Console ]

Use the following procedure to see the status of your Amazon DocumentDB cluster using the AWS Management Console

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.

1. In the **Cluster identifier** column, find the name of the cluster that you are interested in. Then, to find the status of the cluster, read across that row to the **Status** column, as shown below.  
![\[Screenshot of clusters page with sample-cluster showing active status.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cluster-status-con.png)

------
#### [ Using the AWS CLI ]

Use the `describe-db-clusters` operation to see the the status of your Amazon DocumentDB cluster using the AWS CLI. 

The following code finds the status of the cluster `sample-cluster`.

For Linux, macOS, or Unix:

```
aws docdb describe-db-clusters \
    --db-cluster-identifier sample-cluster  \
    --query 'DBClusters[*].[DBClusterIdentifier,Status]'
```

For Windows:

```
aws docdb describe-db-clusters ^
    --db-cluster-identifier sample-cluster  ^
    --query 'DBClusters[*].[DBClusterIdentifier,Status]'
```

Output from this operation looks something like the following (JSON format).

```
[
    [
        "sample-cluster",
        "available"
    ]
]
```

------

# Amazon DocumentDB cluster lifecycle
<a name="db-cluster-life-cycle"></a>

The lifecycle of an Amazon DocumentDB cluster includes creating, describing, modifying, and deleting the cluster. This section provides information about how to complete these processes. 

**Topics**
+ [Creating a cluster](db-cluster-create.md)
+ [Describing clusters](db-cluster-view-details.md)
+ [Modifying a cluster](db-cluster-modify.md)
+ [

# Determining pending maintenance
](db-cluster-determine-pending-maintenance.md)
+ [Patch updating a cluster's engine version](db-cluster-version-upgrade.md)
+ [Stopping and starting a cluster](db-cluster-stop-start.md)
+ [Deleting a cluster](db-cluster-delete.md)

# Creating an Amazon DocumentDB cluster
<a name="db-cluster-create"></a>

An Amazon DocumentDB cluster consists of instances and a cluster volume that represents the data for the cluster. The cluster volume is replicated six ways across three Availability Zones as a single, virtual volume. The cluster contains a primary instance and, optionally, up to 15 replica instances. 

The following sections show how to create an Amazon DocumentDB cluster using either the AWS Management Console or the AWS CLI. You can then add additional replica instances for that cluster. When you use the console to create your Amazon DocumentDB cluster, a primary instance is automatically created for you at the same time. If you use the AWS CLI to create your Amazon DocumentDB cluster, after the cluster's status is *available*, you must then create the primary instance for that cluster.

## Prerequisites
<a name="db-cluster-create-prerequisites"></a>

The following are prerequisites for creating an Amazon DocumentDB cluster.

If you do not have an AWS account, complete the following steps to create one.

**To sign up for an AWS account**

1. Open [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup).

1. Follow the online instructions.

   Part of the sign-up procedure involves receiving a phone call or text message and entering a verification code on the phone keypad.

   When you sign up for an AWS account, an *AWS account root user* is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to perform [tasks that require root user access](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks).

### VPC prerequisites
<a name="db-cluster-create-prerequisites-vpc"></a>

You can only create an Amazon DocumentDB cluster in an Amazon Virtual Private Cloud (Amazon VPC). Your Amazon VPC must have at least one subnet in each of at least two Availability Zones in order for you to use it with an Amazon DocumentDB cluster. By distributing your cluster instances across Availability Zones, you ensure that instances are available in your cluster in the unlikely case of an Availability Zone failure.

### Subnet prerequisites
<a name="db-cluster-create-prerequisites-subnet-groups"></a>

When creating an Amazon DocumentDB cluster, you must choose a VPC and corresponding subnet group within that VPC to launch your cluster. Subnets determine the Availability Zone and IP range within that Availability Zone that you want to use to launch an instance. For the purposes of this discussion, the terms *subnet* and *Availability Zone* are used interchangeably. A subnet group is a named set of subnets (or Availability Zones). What a subnet group allows you to do is specify the Availability Zones that you want to use to for launching Amazon DocumentDB instances. For example, in a cluster with three instances, it is recommended for high availability that each of those instances is provisioned in separate Availability Zones. Thus, if a single Availability Zone goes down, it only affects a single instance.

Amazon DocumentDB instances can currently be provisioned in up to three Availability Zones. Even if a subnet group has more than three subnets, you can only use three of those subnets to create an Amazon DocumentDB cluster. As a result, it is suggested that when you create a subnet group, only choose the three subnets that you want to deploy your instances to. In US East (N. Virginia), your subnet group can have six subnets (or Availability Zones). However, when an Amazon DocumentDB cluster is provisioned, Amazon DocumentDB chooses three of those Availability Zones that it uses to provision instances. 

For example, suppose that when you are creating a cluster, Amazon DocumentDB chooses the Availability Zones \$11A, 1B, and 1C\$1. If you try to create an instance in Availability Zone \$11D\$1, the API call fails. However, if you choose to create an instance without specifying a particular Availability Zone, then Amazon DocumentDB chooses an Availability Zone on your behalf. Amazon DocumentDB uses an algorithm to load balance the instances across Availability Zones to help you achieve high availability. For example, if three instances are provisioned, by default, they are provisioned across three Availability Zones and are not provisioned all in a single Availability Zone.

**Recommendations:**
+ Unless you have a specific reason, always create a subnet group with three subnets. Doing so helps ensure that clusters with three or more instances can achieve higher availability as instances are provisioned across three Availability Zones.
+ Always spread instances across multiple Availability Zones to achieve high availability. Never place all instances for a cluster in a single Availability Zone.
+ Because failover events can happen at any time, you should not assume that a primary instance or replica instances are always in a particular Availability Zone.

### Additional prerequisites
<a name="db-cluster-create-prerequisites-additional"></a>

The following are some additional prerequisites for creating an Amazon DocumentDB cluster:
+ If you are connecting to AWS using AWS Identity and Access Management (IAM) credentials, your IAM account must have IAM policies that grant the permissions that are required to perform Amazon DocumentDB operations.

  If you are using an IAM account to access the Amazon DocumentDB console, you must first sign in to the AWS Management Console with your IAM account. Then go to the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).
+ If you want to tailor the configuration parameters for your cluster, you must specify a cluster parameter group and parameter group with the required parameter settings. For information about creating or modifying a cluster parameter group or parameter group, see [Managing Amazon DocumentDB cluster parameter groups](cluster_parameter_groups.md).
+ You must determine the TCP/IP port number that you want to specify for your cluster. The firewalls at some companies block connections to the default ports for Amazon DocumentDB. If your company firewall blocks the default port, choose another port for your cluster. All instances in a cluster use the same port.

## Creating a cluster and primary instance using the AWS Management Console
<a name="db-cluster-create-con"></a>

The following procedures describe how to use the console to launch an Amazon DocumentDB cluster with one or more instances.

### Create a cluster: using default settings
<a name="db-cluster-create-con-basic"></a>

**To create a cluster with instances using the default settings using the AWS Management Console**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. If you want to create your cluster in an AWS Region other than the US East (N. Virginia) Region, choose the Region from the list in the upper-right section of the console.

1. In the navigation pane, choose **Clusters**, and then choose **Create**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. On the **Create Amazon DocumentDB cluster** page, complete the **Configuration** pane.

   1. **Cluster identifier**—Accept the Amazon DocumentDB provided name, or enter a name for your cluster; for example, **sample-cluster**.

      Cluster naming constraints:
      + Length is [1—63] letters, numbers, or hyphens. 
      + First character must be a letter.
      + Cannot end with a hyphen or contain two consecutive hyphens.
      + Must be unique for all clusters across Amazon RDS, Neptune, and Amazon DocumentDB per AWS account, per Region.

   1. **Engine version**—Accept the default engine version of 5.0.0, or optionally choose 8.0.0, 4.0.0, or 3.6.0.

   1. **Instance class**—Accept the default `db.r5.large`, or choose the instance class that you want from the list.

   1. **Number of instances**—In the list, choose the number of instances that you want to be created with this cluster. The first instance is the primary instance, and all other instances are read-only replica instances. You can add and delete instances later if you need to. By default, an Amazon DocumentDB cluster launches with three instances (one primary and two replicas).

1. Complete the **Cluster storage configuration** section.

   Choose either **Amazon DocumentDB Standard** (default) or **Amazon DocumentDB I/O-Optimized**. For more information, see [Amazon DocumentDB cluster storage configurations](db-cluster-storage-configs.md).

1. Complete the **Authentication** pane.

   1. **Username**—Enter a name for the primary user. To log in to your cluster, you must use the primary user name.

      Primary user naming constraints:
      + Length is [1—63] alphanumeric characters.
      + First character must be a letter.
      + Cannot be a word reserved by the database engine.

   1. Choose one of the following password options:
      + **Managed in AWS Secrets Manager**—Choose this option if you want AWS Secrets Manager to automatically manage your primary user password.

        If you choose this option, configure the KMS key by either creating your own or using a key that Secrets Manager creates.
      + **Self managed**—Choose this option if you want to self-manage your primary user password. If you choose this option, enter a password for the primary user, and then confirm it. To log in to your cluster, you must use the password for the primary user.

        Password constraints:
        + Length is [8-100] printable ASCII characters.
        + Can use any printable ASCII characters except for the following:
          + **/** (forward slash)
          + **"** (double quotation mark)
          + **@** (at symbol)

1. At the bottom of the screen, choose one of the following:
   + To create the cluster now, choose **Create cluster**.
   + To not create the cluster, choose **Cancel**.
   + To further configure the cluster before creating, choose **Show additional configurations**, and then continue at [Create a cluster: additional configurations](#db-cluster-create-con-additional-configs).

     The configurations covered in the **Additional Configurations** section are as follows:
     + **Network settings**—The default is to use the `default` VPC security group.
     + **Cluster options**—The default is to use port is 27017 and the default parameter group.
     + **Encryption**—The default is to enable encryption using the `(default) aws/rds` key.
**Important**  
After a cluster is encrypted, it cannot be unencrypted.
     + **Backup**—The default is to retain backups for 1 day and let Amazon DocumentDB choose the backup window.
     + **Log exports**—The default is to not export audit logs to CloudWatch Logs.
     + **Maintenance**—The default is to let Amazon DocumentDB choose the maintenance window.
     + **Deletion protection**—Protect your cluster from accidental deletion. Default for cluster created using the console is *enabled*.

     If you accept the default settings now, you can change most of them later by modifying the cluster.

1. Enable inbound connection for your cluster's security group.

   If you did not change the defaults settings for your cluster, you created a cluster using the default security group for the default VPC in the given region. To connect to Amazon DocumentDB, you must enable inbound connections on port 27017 (or the port of your choice) for your cluster’s security group.

   **To add an inbound connection to your cluster's security group**

   1. Sign in to the AWS Management Console and open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

   1. In the **Resources** section of the main window, choose **Security groups**.  
![\[Image: Resources list highlighting the Security Groups link option.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-ec2-security-groups.png)

   1. From the list of security groups locate the security group you used when creating your cluster (it is most likely the *default* security group) and choose the box to the left of the security group's name.  
![\[Image: Security groups list highlighting one security group with box selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-ec2-default-sg.png)

   1. From the **Actions** menu, choose **Edit inbound rules** then choose or enter the rule constraints.

      1. **Type**—From the list, choose the protocol to open to network traffic.

      1. **Protocol**—From the list, choose the type of protocol.

      1. **Port Range**—For a custom rule, enter a port number or port range. Be sure that the port number or range includes the port you specified when you created your cluster (default: 27017).

      1. **Source**—Specifies the traffic that can reach your instance. From the list, choose the traffic source. If you choose **Custom**, specify a single IP address or an IP address range in CIDR notation (e.g., 203.0.113.5/32).

      1. **Description**—Enter a description for this rule.

      1. When finished creating the rule, choose **Save**.

### Create a cluster: additional configurations
<a name="db-cluster-create-con-additional-configs"></a>

If you want to accept the default settings for your cluster, you can skip the following steps and choose **Create cluster**. 

1. Complete the **Network settings** pane.  
![\[Screenshot showing the network settings pane and the steps to configure the network settings.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/create-db-cluster-console-network-settings.png)

   1. **Virtual Private Cloud (VPC)**—In the list, choose the Amazon VPC that you want to launch this cluster in.

   1. **Subnet group**—In the list, choose the subnet group you want to use for this cluster.

   1. **VPC security groups**—In the list, choose the VPC security group for this cluster.

1. Complete the **Cluster options** pane.  
![\[Screenshot showing the cluster options pane with the steps to configure the cluster settings.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/create-db-cluster-console-cluster-options.png)

   1. **Data base port**—Use the up and down arrows to set the TCP/IP port that applications will use to connect to your instance.

   1. **Cluster parameter group**—In the list of parameter groups, choose the cluster parameter group for this cluster.

1. Complete the **Encryption** pane.  
![\[Screenshot of the encryption pane showing the steps to configure encryption for the cluster.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/encrypt-at-rest.png)

   1. **Encryption-at-rest**—Choose one of the following:
      + **Enable encryption**—Default. All data at rest is encrypted. If you choose to encrypt your data, you cannot undo this action.
      + **Disable encryption**—Your data is not encrypted.

   1. **AWS KMS key**—This is only available if you are encrypting your data. In the list, choose the key that you want to use for encrypting the data in this cluster. The default is `(default) aws/rds`.

      If you chose **Enter a key ARN**, you must enter an Amazon Resource Name (ARN) for the key.

1. Complete the **Backup** pane.  
![\[Screenshot of the Backup pane showing the steps to configure the cluster backup window.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/create-db-cluster-console-backup.png)

   1. **Backup retention period**—In the list, choose the number of days to keep automatic backups of this cluster before deleting them.

   1. **Backup window**—Set the daily time and duration during which Amazon DocumentDB is to make backups of this cluster.

      1. **Start time**—In the first list, choose the start time hour (UTC) for starting your automatic backups. In the second list, choose the minute of the hour that you want automatic backups to begin.

      1. **Duration**—In the list, choose the number of hours to be allocated to creating automatic backups.

1. Complete the **Log exports** pane by selecting the types of logs you want to export to CloudWatch Logs.  
![\[Screenshot of the Log exports pane showing the steps to configure the cluster's DML logging.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/create-db-cluster-console-log-exports.png)
   + **Audit logs**—Select this option to enable exporting audit logs to Amazon CloudWatch Logs. If you select **Audit logs**, you must enable `audit_logs` in the cluster's custom parameter group. For more information, see [Auditing Amazon DocumentDB events](event-auditing.md).
   + **Profiler logs**—Select this option to enable exporting operation profiler logs to Amazon CloudWatch Logs. If you select **Profiler logs**, you must also modify the following parameters in the cluster's custom parameter group:
     + `profiler`—Set to `enabled`.
     + `profiler_threshold_ms`—Set to a value `[0-INT_MAX]` to set the threshold for profiling operations.
     + `profiler_sampling_rate`—Set to a value `[0.0-1.0]` to set the percentage of slow operations to profile.

     For more information, see [Profiling Amazon DocumentDB operations](profiling.md).

1. Complete the **Maintenance** pane.  
![\[Screenshot of the Maintenance pane showing the steps to configure the cluster's maintenance window.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/create-db-cluster-console-maintenance.png)

   1. Choose one of the following
     + **Select window**—You can specify the day of the week, UTC start time, and duration for Amazon DocumentDB to perform maintenance on your cluster.

       1. **Start day**—In the list, choose the day of the week to start cluster maintenance.

       1. **Start time**—In the lists, choose the hour and minute (UTC) to start maintenance.

       1. **Duration**—In the list, choose how much time to allocate for cluster maintenance. If maintenance cannot be finished in the specified time, the maintenance process will continue past the specified time until finished.
     + **No preference**—Amazon DocumentDB chooses the day of the week, start time, and duration for performing maintenance.

1. If you want to add one or more tags to this cluster, complete the **Tags** pane.  
![\[Screenshot of the Enable deletion protection checkbox, which is selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/create-db-cluster-console-tags.png)

   For each tag you want to add to the cluster, repeat the following steps. You may have up to 10 on a cluster.

   1. Choose **Add tags**.

   1. Type the tag's **Key**.

   1. Optionally type the tag's **Value**.

   To remove a tag, choose **Remove tag**.

1. **Deletion Protection** is enabled by default when you create a cluster using the console. To disable deletion protection, clear **Enable deletion protection**. When enabled, deletion protection prevents a cluster from being deleted. To delete a deletion protected cluster, you must first modify the cluster to disable deletion protection.  
![\[Screenshot of the Enable deletion protection checkbox, which is selected.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/create-db-cluster-console-deletion-protection.png)

   For more information about deletion protection, see [Deleting an Amazon DocumentDB cluster](db-cluster-delete.md).

1. To create the cluster, choose **Create cluster**. Otherwise, choose **Cancel**.

## Creating a cluster using the AWS CLI
<a name="db-cluster-create-cli"></a>

The following procedures describe how to use the AWS CLI to launch an Amazon DocumentDB cluster and create an Amazon DocumentDB replica.

**Parameters**
+ **--db-cluster-identifier**—Required. A lowercase string that identifies this cluster.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-create.html)
+ **--engine**—Required. Must be **docdb**.
+ **--deletion-protection \$1 --no-deletion-protection**—Optional. When deletion protection is enabled, it prevents a cluster from being deleted. When you use the AWS CLI, the default setting is to have deletion protection disabled.

  For more information about deletion protection, see [Deleting an Amazon DocumentDB cluster](db-cluster-delete.md).
+ **--storage-type standard \$1 iopt1**—Optional. Default: **standard**. The cluster's storage configuration. Valid values are `standard` (Standard) or `iopt1` (I/O-optimized).
+ **--master-username**—Required. The user name used to authenticate the user.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-create.html)
+ **--master-user-password**—Optional. The user's password used to authenticate the user.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-create.html)
+ **--manage-master-user-password**—Optional. Amazon DocumentDB generates the master user password and manages it throughout its lifecycle in Secrets Manager.

For additional parameters, see [CreateDBCluster](API_CreateDBCluster.md).

**To launch an Amazon DocumentDB cluster using the AWS CLI**

To create an Amazon DocumentDB cluster, call the `create-db-cluster` AWS CLI. The following AWS CLI command creates an Amazon DocumentDB cluster named `sample-cluster` with deletion protection enabled. For more information on deletion protection, see [Deleting an Amazon DocumentDB cluster](db-cluster-delete.md).

Also, `--engine-version` is an optional parameter that defaults to the latest major engine version. The current default engine version is 5.0.0 (note: Amazon DocumentDB 8.0 is available but must be explicitly specified). When new major engine versions are released, the default engine version for `--engine-version` will be updated to reflect the last major engine version. As a result, for production workloads, and especially those that are dependent on scripting, automation, or CloudFormation templates, we recommend that you explicitly specify the `--engine-version` to the intended major version.

**Note**  
If a `db-subnet-group-name` or `vpc-security-group-id` is not specified, Amazon DocumentDB will use the default subnet group and Amazon VPC security group for the given region.

For Linux, macOS, or Unix:

```
aws docdb create-db-cluster \
      --db-cluster-identifier sample-cluster \
      --engine docdb \
      --engine-version 5.0.0 \
      --deletion-protection \
      --master-username masteruser \
      --master-user-password password
```

For Windows:

```
aws docdb create-db-cluster ^
      --db-cluster-identifier sample-cluster ^
      --engine docdb ^
      --engine-version 5.0.0 ^
      --deletion-protection ^
      --master-username masteruser ^
      --master-user-password password
```

Output from this operation looks something like the following (JSON format).

```
{
    "DBCluster": {
        "StorageEncrypted": false,
        "DBClusterMembers": [],
        "Engine": "docdb",
        "DeletionProtection" : "enabled",
        "ClusterCreateTime": "2018-11-26T17:15:19.885Z",
        "DBSubnetGroup": "default",
        "EngineVersion": "5.0.0",
        "MasterUsername": "masteruser",
        "BackupRetentionPeriod": 1,
        "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster",
        "DBClusterIdentifier": "sample-cluster",
        "MultiAZ": false,
        "DBClusterParameterGroup": "default.docdb5.0",
        "PreferredBackupWindow": "09:12-09:42",
        "DbClusterResourceId": "cluster-KQSGI4MHU4NTDDRVNLNTU7XVAY",
        "PreferredMaintenanceWindow": "tue:04:17-tue:04:47",
        "Port": 27017,
        "Status": "creating",
        "ReaderEndpoint": "sample-cluster.cluster-ro-sfcrlcjcoroz.us-east-1.docdb.amazonaws.com",
        "AssociatedRoles": [],
        "HostedZoneId": "ZNKXTT8WH85VW",
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-77186e0d",
                "Status": "active"
            }
        ],
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1c",
            "us-east-1e"
        ],
        "Endpoint": "sample-cluster.cluster-sfcrlcjcoroz.us-east-1.docdb.amazonaws.com"
    }
}
```

It takes several minutes to create the cluster. You can use the AWS Management Console or AWS CLI to monitor the status of your cluster. For more information, see [Monitoring an Amazon DocumentDB cluster's status](monitoring_docdb-cluster_status.md). 

**Important**  
When you use the AWS CLI to create an Amazon DocumentDB cluster, no instances are created. Consequently, you must explicitly create a primary instance and any replica instances that you need. You can use either the console or AWS CLI to create the instances. For more information, see [Adding an Amazon DocumentDB instance to a cluster](db-instance-add.md). 

For more information, see [https://docs.aws.amazon.com/documentdb/latest/developerguide/API_CreateDBCluster.html](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_CreateDBCluster.html) in the *Amazon DocumentDB API Reference*. 

# Describing Amazon DocumentDB clusters
<a name="db-cluster-view-details"></a>

You can use either Amazon DocumentDB Management Console or the AWS CLI to see details such as connection endpoints, security groups, VPCs, and parameter groups pertaining to your Amazon DocumentDB clusters.

For more information, see the following:
+ [Monitoring an Amazon DocumentDB cluster's status](monitoring_docdb-cluster_status.md)
+ [Finding a cluster's endpoints](db-cluster-endpoints-find.md)

------
#### [ Using the AWS Management Console ]

Use the following procedure to view the details of a specified Amazon DocumentDB cluster using the console.

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the list of clusters, choose the name of the cluster that you want to see the details of. The information about the cluster is organized into the following groupings:
   + **Summary** — General information about the cluster, including the engine version, cluster status, pending maintenance, and the status of its parameter group.
   + **Connectivity & Security** —The **Connect** section lists connection endpoints to connect to this cluster with the mongo shell or with an application. The **Security Groups** section lists the security groups associated with this cluster and their VPC ID and descriptions. 
   + **Configuration** — The **Cluster details** section lists details about the cluster, including the cluster's Amazon Resource Name (ARN), endpoint, and parameter group. It also lists the cluster's backup information, maintenance details, and security and network settings. The **Cluster instances** section lists the instances that belong to this cluster with each instance's role and cluster parameter group status.
   + **Monitoring** — The Amazon CloudWatch Logs metrics for this cluster. For more information, see [Monitoring Amazon DocumentDB with CloudWatch](cloud_watch.md).
   + **Events & tags** — The **Recent events** section lists the recent events for this cluster. Amazon DocumentDB keeps a record of events that relate to your clusters, instances, snapshots, security groups, and cluster parameter groups. This information includes the date, time, and message associated with each event. The **Tags** section lists the tags attached to this cluster.

------
#### [ Using the AWS CLI ]

To view the details of your Amazon DocumentDB clusters using the AWS CLI, use the `describe-db-clusters` command as shown in the examples below. For more information, see [https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DescribeDBClusters.html](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DescribeDBClusters.html) in the *Amazon DocumentDB Resource Management API Reference*. 

**Note**  
For certain management features such as cluster and instance lifecycle management, Amazon DocumentDB leverages operational technology that is shared with Amazon RDS. The `filterName=engine,Values=docdb` filter parameter returns only Amazon DocumentDB clusters. 

**Example**  
**Example 1: List all Amazon DocumentDB clusters **  
The following AWS CLI code lists the details for all Amazon DocumentDB clusters in a region.   

```
aws docdb describe-db-clusters --filter Name=engine,Values=docdb
```
Output from this operation looks something like the following.  

```
{
    "DBClusters": [
        {
            "AvailabilityZones": [
                "us-east-1c",
                "us-east-1b",
                "us-east-1a"
            ],
            "BackupRetentionPeriod": 1,
            "DBClusterIdentifier": "sample-cluster-1",
            "DBClusterParameterGroup": "sample-parameter-group",
            "DBSubnetGroup": "default",
            "Status": "available",
            ...
        },
        {
            "AvailabilityZones": [
                "us-east-1c",
                "us-east-1b",
                "us-east-1a"
            ],
            "BackupRetentionPeriod": 1,
            "DBClusterIdentifier": "sample-cluster-2",
            "DBClusterParameterGroup": "sample-parameter-group",
            "DBSubnetGroup": "default",
            "Status": "available",
            ...
        },
        {
            "AvailabilityZones": [
                "us-east-1c",
                "us-east-1b",
                "us-east-1a"
            ],
            "BackupRetentionPeriod": 1,
            "DBClusterIdentifier": "sample-cluster-3",
            "DBClusterParameterGroup": "sample-parameter-group",
            "DBSubnetGroup": "default",
            "Status": "available",
            ...
        }
    ]
}
```

**Example**  
**Example 2: List all details for a specified Amazon DocumentDB cluster**  
The following AWS CLI code lists the details for the cluster `sample-cluster`.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-clusters \
   --filter Name=engine,Values=docdb \
   --db-cluster-identifier sample-cluster
```
For Windows:  

```
aws docdb describe-db-clusters ^
   --filter Name=engine,Values=docdb ^
   --db-cluster-identifier sample-cluster
```
Output from this operation looks something like the following.  

```
{
    "DBClusters": [
        {
            "AllocatedStorage": 1,
            "AvailabilityZones": [
                "us-east-1c",
                "us-east-1a",
                "us-east-1d"
            ],
            "BackupRetentionPeriod": 2,
            "DBClusterIdentifier": "sample-cluster",
            "DBClusterParameterGroup": "sample-parameter-group",
            "DBSubnetGroup": "default",
            "Status": "available",
            "EarliestRestorableTime": "2023-11-07T22:34:08.148000+00:00",
            "Endpoint": "sample-cluster.node.us-east-1.amazon.com",
            "ReaderEndpoint": "sample-cluster.node.us-east-1.amazon.com",
            "MultiAZ": false,
            "Engine": "docdb",
            "EngineVersion": "5.0.0",
            "LatestRestorableTime": "2023-11-10T07:21:16.772000+00:00",
            "Port": 27017,
            "MasterUsername": "chimeraAdmin",
            "PreferredBackupWindow": "22:22-22:52",
            "PreferredMaintenanceWindow": "sun:03:01-sun:03:31",
            "ReadReplicaIdentifiers": [],
            "DBClusterMembers": [
                {
                    "DBInstanceIdentifier": "sample-instance-1",
                    "IsClusterWriter": true,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "PromotionTier": 1
                },
                {
                    "DBInstanceIdentifier": "sample-instance-2",
                    "IsClusterWriter": true,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "PromotionTier": 1
                },
                
            ],
            "VpcSecurityGroups": [
                {
                    "VpcSecurityGroupId": "sg-9084c2ec",
                    "Status": "active"
                }
            ],
            "HostedZoneId": "Z06853723JYKYBXTJ49RB",
            "StorageEncrypted": false,
            "DbClusterResourceId": "cluster-T4LGLANHVAPGQYYULWUDKLVQL4",
            "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster",
            "AssociatedRoles": [],
            "IAMDatabaseAuthenticationEnabled": false,
            "ClusterCreateTime": "2023-11-06T18:05:41.568000+00:00",
            "EngineMode": "provisioned",
            "DeletionProtection": false,
            "HttpEndpointEnabled": false,
            "CopyTagsToSnapshot": false,
            "CrossAccountClone": false,
            "DomainMemberships": [],
            "TagList": [],
            "StorageType": "iopt1",
            "AutoMinorVersionUpgrade": false,
            "NetworkType": "IPV4",
            "IOOptimizedNextAllowedModificationTime": "2023-12-07T18:05:41.580000+00:00"
        }
    ]
}
```

**Example**  
**Example 3: List specific details for a Amazon DocumentDB cluster**  
To list a subset of the clusters' details using the AWS CLI, add a `--query` that specifies which cluster members the `describe-db-clusters` operation is to list. The `--db-cluster-identifier` parameter is the identifier for the particular cluster that you want to display the details of. For more information on queries, see [ How to Filter the Output with the `--query` Option](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-output.html#controlling-output-filter) in the *AWS Command Line Interface User Guide*.   
The following example lists the instances in an Amazon DocumentDB cluster.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-clusters \
    --filter Name=engine,Values=docdb \
    --db-cluster-identifier sample-cluster \
    --query 'DBClusters[*].[DBClusterMembers]'
```
For Windows:  

```
aws docdb describe-db-clusters ^
    --filter Name=engine,Values=docdb ^
    --db-cluster-identifier sample-cluster ^
    --query 'DBClusters[*].[DBClusterMembers]'
```
Output from this operation looks something like the following.  

```
[
    [
        [
            {
                "DBInstanceIdentifier": "sample-instance-1",
                "IsClusterWriter": true,
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1
            },
            {
                "DBInstanceIdentifier": "sample-instance-2",
                "IsClusterWriter": false,
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1
            }
        ]
    ]
]
```

------

# Modifying an Amazon DocumentDB cluster
<a name="db-cluster-modify"></a>

To modify a cluster, the cluster must be in the *available* state. You cannot modify a cluster that is stopped. If the cluster is stopped, first start the cluster, wait for the cluster to become *available*, and then make the desired modifications. For more information, see [Stopping and starting an Amazon DocumentDB cluster](db-cluster-stop-start.md). 

------
#### [ Using the AWS Management Console ]

Use the following procedure to modify a specific Amazon DocumentDB cluster using the console.

**To modify an Amazon DocumentDB cluster**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. Specify the cluster that you want to modify by choosing the button to the left of the cluster's name.

1. Choose **Actions**, and then choose **Modify**.

1. In the **Modify Cluster: <cluster-name>** pane, make the changes that you want. You can make changes in the following areas:
   + **Cluster specifications**—The cluster's name, security groups, and credentials management.
   + **Cluster storage configuration**—The cluster's data storage mode. Choose between Standard and I/O-Optimized configuration.
   + **Cluster options**—The cluster's port and parameter group.
   + **Backup**—The cluster's backup retention period and backup window.
   + **Log exports**—Enable or disable exporting audit or profiler logs.
   + **Maintenance**—Set the cluster's maintenance window.
   + **Deletion protection**—Enable or disable deletion protection on the cluster. Deletion protection is enabled by default.

1. When you're finished, choose **Continue** to view a summary of your changes.

1. If you are satisfied with your changes, you can choose **Modify cluster** to modify your cluster. Alternatively, you can choose **Back** or **Cancel** to edit or cancel your changes, respectively. 

It takes a few minutes for your changes to be applied. You can use the cluster only when its status is *available*. You can monitor the cluster's status using the console or AWS CLI. For more information, see [Monitoring an Amazon DocumentDB cluster's status](monitoring_docdb-cluster_status.md). 

------
#### [ Using the AWS CLI ]

Use the `modify-db-cluster` operation to modify the specified cluster using the AWS CLI. For more information, see [https://docs.aws.amazon.com/documentdb/latest/developerguide/API_ModifyDBCluster.html](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_ModifyDBCluster.html) in the *Amazon DocumentDB API Reference*.

**Parameters**
+ **--db-cluster-identifier**—Required. The identifier of the Amazon DocumentDB cluster that you are going to modify.
+ **--backup-retention-period**—Optional. The number of days for which automated backups are retained. Valid values are 1–35.
+ **--storage-type**—Optional. The cluster's storage configuration. Valid values are `standard` (Standard) or `iopt1` (I/O-optimized).
+ **--db-cluster-parameter-group-name**—Optional. The name of the cluster parameter group to use for the cluster.
+ **--manage-master-user-password**—Optional. Amazon DocumentDB generates the master user password and manages it throughout its lifecycle in Secrets Manager.
+ **--rotate-master-user-password**—Optional. Secrets Manager generates a new secret version for the existing secret. The new version of the secret contains the new primary user password. Amazon DocumentDB changes the primary user password for the cluster to match the password for the new secret version.

  You must specify the **--apply-immediately** option when you rotate the primary password.
+ **--master-user-password**—Optional. The new password for the primary database user.

  Password constraints:
  + Length is [8—100] printable ASCII characters.
  + Can use any printable ASCII characters except for the following:
    + **/** (forward slash)
    + **"** (double quotation mark)
    + **@** (at symbol)
+ **--new-db-cluster-identifier**—Optional. The new cluster identifier for the cluster when renaming a cluster. This value is stored as a lowercase string.

  Naming constraints:
  + Length is [1—63] letters, numbers, or hyphens.
  + First character must be a letter.
  + Cannot end with a hyphen or contain two consecutive hyphens.
  + Must be unique for all clusters across Amazon RDS, Amazon Neptune, and Amazon DocumentDB per AWS account, per region.
+ **--preferred-backup-window**—Optional. The daily time range during which automated backups are created, in Universal Coordinated Time (UTC).
  + Format: `hh24:mm-hh24:mm`
+ **--preferred-maintenance-window**—Optional. The weekly time range during which system maintenance can occur, in UTC.
  + Format: `ddd:hh24:mm-ddd:hh24:mm`
  + Valid days: `Sun`, `Mon`, `Tue`, `Wed`, `Thu`, `Fri`, and `Sat`.
+ **--deletion-protection** or **--no-deletion-protection**—Optional. Whether deletion protection should be enabled on this cluster. Deletion protection prevents a cluster from being accidentally deleted until the cluster is modified to disable deletion protection. For more information, see [Deleting an Amazon DocumentDB cluster](db-cluster-delete.md). 
+ **--apply-immediately** or **--no-apply-immediately**—Use `--apply-immediately` to make the change immediately. Use `--no-apply-immediately` to make the change during your cluster's next maintenance window.

**Example**  
The following code changes the backup retention period for the cluster `sample-cluster`.  
For Linux, macOS, or Unix:  

```
aws docdb modify-db-cluster \
       --db-cluster-identifier sample-cluster \
       --apply-immediately \
       --backup-retention-period 7
```
For Windows:  

```
aws docdb modify-db-cluster ^
       --db-cluster-identifier sample-cluster ^
       --apply-immediately ^
       --backup-retention-period 7
```
Output from this operation looks something like the following.  

```
{
    "DBCluster": {
        "BackupRetentionPeriod": 7,
        "DbClusterResourceId": "cluster-VDP53QEWST7YHM36TTXOPJT5YE",
        "Status": "available",
        "DBClusterMembers": [
            {
                "PromotionTier": 1,
                "DBClusterParameterGroupStatus": "in-sync",
                "DBInstanceIdentifier": "sample-cluster-instance",
                "IsClusterWriter": true
            }
        ],
        "ReadReplicaIdentifiers": [],
        "AvailabilityZones": [
            "us-east-1b",
            "us-east-1c",
            "us-east-1a"
        ],
        "ReaderEndpoint": "sample-cluster.cluster-ro-ctevjxdlur57.us-east-1.rds.amazonaws.com",
        "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster",
        "PreferredMaintenanceWindow": "sat:09:51-sat:10:21",
        "EarliestRestorableTime": "2018-06-17T00:06:19.374Z",
        "StorageEncrypted": false,
        "MultiAZ": false,
        "AssociatedRoles": [],
        "MasterUsername": "<your-master-user-name>",
        "DBClusterIdentifier": "sample-cluster",
        "VpcSecurityGroups": [
            {
                "Status": "active",
                "VpcSecurityGroupId": "sg-77186e0d"
            }
        ],
        "HostedZoneId": "Z2SUY0A1719RZT",
        "LatestRestorableTime": "2018-06-18T21:17:05.737Z",
        "AllocatedStorage": 1,
        "Port": 27017,
        "Engine": "docdb",
        "DBClusterParameterGroup": "default.docdb3.4",
        "Endpoint": "sample-cluster.cluster-ctevjxdlur57.us-east-1.rds.amazonaws.com",
        "DBSubnetGroup": "default",
        "PreferredBackupWindow": "00:00-00:30",
        "EngineVersion": "3.4",
        "ClusterCreateTime": "2018-06-06T19:25:47.991Z",
        "IAMDatabaseAuthenticationEnabled": false
    }
}
```

It takes a few minutes for your changes to be applied. You can use the cluster only when its status is *available*. You can monitor the cluster's status using the console or AWS CLI. For more information, see [Monitoring an Amazon DocumentDB cluster's status](monitoring_docdb-cluster_status.md). 

------

# Determining pending maintenance
<a name="db-cluster-determine-pending-maintenance"></a>

You can determine whether you have the latest Amazon DocumentDB engine version by determining whether you have pending cluster maintenance.

------
#### [ Using the AWS Management Console ]

You can use the AWS Management Console to determine whether a cluster has pending maintenance.

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. Locate the **Maintenance** column to determine whether a cluster has pending maintenance.  
![\[Console screenshot showing Amazon DocumentDB cluster maintenance field.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-cluster-pending-maintenance.png)

   **None** indicates that the cluster is running the latest engine version. **Available** indicates that the cluster has pending maintenance, which might mean that an engine upgrade is needed.

1. If your cluster has pending maintenance, continue with the steps at [Performing a patch update to a cluster's engine version](db-cluster-version-upgrade.md). 

------
#### [ Using the AWS CLI ]

You can use the AWS CLI to determine whether a cluster has the latest engine version by using the `describe-pending-maintenance-actions` operation with the following parameters.

**Parameters**
+ **--resource-identifier**—Optional. The ARN for the resource (cluster). If this parameter is omitted, pending maintenance actions for all clusters are listed.
+ **--region**—Optional. The AWS Region that you want to run this operation in, for example, `us-east-1`.

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb describe-pending-maintenance-actions \
   --resource-identifier arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster \
   --region us-east-1
```
For Windows:  

```
aws docdb describe-pending-maintenance-actions ^
   --resource-identifier arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster ^
   --region us-east-1
```
Output from this operation looks something like the following.  

```
{
    "PendingMaintenanceActions": [
        {
            "ResourceIdentifier": "arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster",
            "PendingMaintenanceActionDetails": [
                {
                    "Description": "New feature",
                    "Action": "db-upgrade",
                    "ForcedApplyDate": "2019-02-25T21:46:00Z",
                    "AutoAppliedAfterDate": "2019-02-25T07:41:00Z",
                    "CurrentApplyDate": "2019-02-25T07:41:00Z"
                }
            ]
        }
    ]
}
```

If your cluster has pending maintenance, continue with the steps at [Performing a patch update to a cluster's engine version](db-cluster-version-upgrade.md). 

------

# Performing a patch update to a cluster's engine version
<a name="db-cluster-version-upgrade"></a>

In this section, we will explain how to deploy a patch update using the AWS Management Console or the AWS CLI. A patch update is an update within the same engine version (for example, updating a 3.6 engine version to a newer 3.6 engine version). You can update it immediately or during your cluster's next maintenance window. To determine whether your engine needs an update, see [Determining pending maintenance](db-cluster-determine-pending-maintenance.md). Please note that when you apply the update, your cluster will experience some downtime.

**Note**  
If you are trying to upgrade from a major engine version to another, such as 3.6 to 5.0, see either [Amazon DocumentDB in-place major version upgrade](docdb-mvu.md) or [Upgrading your Amazon DocumentDB cluster using AWS Database Migration Service](docdb-migration.versions.md). An in-place major version upgrade only supports docdb 5.0 as the target engine version.

There are two configuration requirements to get the latest patch updates for a cluster's engine version:
+ The cluster's status must be *available*.
+ The cluster must be running an earlier engine version.

------
#### [ Using the AWS Management Console ]

The following procedure applies patch updates to your cluster's engine version using the console. You have the option to update immediately or during your cluster's next maintenance window.

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**. In the list of clusters, choose the button to the left of the cluster that you want to upgrade. The status of the cluster must be *available*.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. From the **Actions** menu, choose one of the following options. These menu options are selectable only if the cluster you chose is not running the latest engine version.  
![\[Image: Amazon DocumentDB Upgrade actions\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-upgrade-action.png)
   + **Upgrade now**—Immediately initiates the upgrade process. Your cluster will be offline for a time while the cluster is upgraded to the latest engine version.
   + **Upgrade at next window**—Initiates the upgrade process during the cluster's next maintenance window. Your cluster will be offline for a time while it is upgraded to the latest engine version.

1. When the confirmation window opens, choose one of the following:
   + **Upgrade**—To upgrade your cluster to the latest engine version according to the schedule chosen in the previous step.
   + **Cancel**—To cancel the cluster's engine upgrade and continue with the cluster's current engine version.

------
#### [ Using the AWS CLI ]

You can apply patch updates to your cluster using the AWS CLI and the `apply-pending-maintenance-action` operation with the following parameters.

**Parameters**
+ **--resource-identifier**—Required. The ARN of the Amazon DocumentDB cluster that you are going to upgrade.
+ **--apply-action**—Required. The following values are permitted. To upgrade your cluster engine version, use `db-upgrade`.
  + **db-upgrade**
  + **system-update**
+ **--opt-in-type**—Required. The following values are permitted.
  + `immediate`—Apply the maintenance action immediately.
  + `next-maintenance`—Apply the maintenance action during the next maintenance window.
  + `undo-opt-in`—Cancel any existing `next-maintenance` opt-in requests.

**Example**  
The following example patch updates the engine version of `sample-cluster` to version 4.0.0.  
For Linux, macOS, or Unix:  

```
aws docdb apply-pending-maintenance-action \
   --resource-identifier arn:aws:rds:us-east-1:123456789012\:cluster:sample-cluster \
   --apply-action db-upgrade \
   --opt-in-type immediate
```
For Windows:  

```
aws docdb apply-pending-maintenance-action ^
   --resource-identifier arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster ^
   --apply-action db-upgrade ^
   --opt-in-type immediate
```
Output from this operation looks like the following.  

```
{
    "ResourcePendingMaintenanceActions": {
        "ResourceIdentifier": "arn:aws:rds:us-east-1:444455556666:cluster:docdb-2019-01-09-23-55-38",
        "PendingMaintenanceActionDetails": [
            {
                "CurrentApplyDate": "2019-02-20T20:57:06.904Z",
                "Description": "Bug fixes",
                "ForcedApplyDate": "2019-02-25T21:46:00Z",
                "OptInStatus": "immediate",
                "Action": "db-upgrade",
                "AutoAppliedAfterDate": "2019-02-25T07:41:00Z"
            }
        ]
    }
}
```

------

# Stopping and starting an Amazon DocumentDB cluster
<a name="db-cluster-stop-start"></a>

Stopping and starting Amazon DocumentDB clusters can help you manage costs for development and test environments. Instead of creating and deleting clusters and instances each time you use Amazon DocumentDB, you can temporarily stop all the instances in your cluster when they aren't needed. You can then start them again when you resume your testing.

**Topics**
+ [

## Overview of stopping and starting a cluster
](#db-cluster-stop-start-overview)
+ [

## Operations you can perform on a stopped cluster
](#db-cluster-stopped-operations)

## Overview of stopping and starting a cluster
<a name="db-cluster-stop-start-overview"></a>

During periods where you don't need an Amazon DocumentDB cluster, you can stop all instances in that cluster at once. You can then start the cluster again anytime you need to use it. Starting and stopping simplifies the setup and teardown processes for clusters that are used for development, testing, or similar activities that don't require continuous availability. You can stop and start a cluster using the AWS Management Console or the AWS CLI with a single action, regardless of how many instances are in the cluster.

While your cluster is stopped, the cluster storage volume remains unchanged. You are charged only for storage, manual snapshots, and automated backup storage within your specified retention window. You aren't charged for any instance hours. Amazon DocumentDB automatically starts your cluster after seven days so that it doesn't fall behind any required maintenance updates. When your cluster starts after seven days, you will begin to be charged for the instances in the cluster again. While your cluster is stopped, you can't query your storage volume because querying requires that instances are in the available state.

When an Amazon DocumentDB cluster is stopped, neither the cluster nor its instances can be modified in any way. This includes adding or removing instances, or deleting the cluster.

------
#### [ Using the AWS Management Console ]

The following procedure shows you how to stop a cluster with one or more instances in the available state, or start a stopped cluster.

**To stop or start an Amazon DocumentDB cluster**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the list of clusters, choose the button to the left of the name of the cluster that you want to stop or start.

1. Choose **Actions**, and then choose the action that you want to perform on the cluster.
   + If you want to stop the cluster and the cluster is available:

     1. Choose **Stop**.  
![\[Image: Stop a cluster\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cluster-stop.png)

        To avoid activating the failover mechanism, the stop operation stops the replica instances first, and then the primary instance.

     1. On the confirmation dialog, confirm that you want to stop the cluster by choosing **Stop cluster**, or to keep the cluster running, choose **Cancel**.  
![\[Image: Start a cluster\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cluster-stop-confirm.png)
   + If you want to start the cluster, and the cluster is stopped, choose **Start**.  
![\[Image: Start a cluster\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cluster-start.png)

1. Monitor the status of the cluster and its instances. If you started the cluster, you can resume using the cluster when the cluster and its instances are *available*. For more information, see [Determining a cluster's status](db-cluster-status.md).   
![\[Image: Status of clusters stopping and starting\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cluster-stop-start-status.png)

------
#### [ Using the AWS CLI ]

The following code examples show you how to stop a cluster with one or more instances in the available state, or start a stopped cluster.

To stop a cluster with one or more available instances using the AWS CLI, use the `stop-db-cluster` operation. To start a stopped cluster, use the `start-db-cluster` operation. Both operations use the `--db-cluster-identifier` parameter.

**Parameter:**
+ **--db-cluster-identifier**—Required. The name of the cluster to stop or start.

**Example — To stop a cluster using the AWS CLI**  
The following code stops the cluster `sample-cluster`. The cluster must have one or more instances in the available state.  
For Linux, macOS, or Unix:  

```
aws docdb stop-db-cluster \
   --db-cluster-identifier sample-cluster
```
For Windows:  

```
aws docdb stop-db-cluster ^
   --db-cluster-identifier sample-cluster
```

**Example — To start a cluster using the AWS CLI**  
The following code starts the cluster `sample-cluster`. The cluster must currently be stopped.  
For Linux, macOS, or Unix:  

```
aws docdb start-db-cluster \
   --db-cluster-identifier sample-cluster
```
For Windows:  

```
aws docdb start-db-cluster ^
   --db-cluster-identifier sample-cluster
```

------

## Operations you can perform on a stopped cluster
<a name="db-cluster-stopped-operations"></a>

While an Amazon DocumentDB cluster is stopped, you can do a point-in-time restore to any point within your specified automated backup retention window. For details about doing a point-in-time restore, see [Restoring to a point in time](backup_restore-point_in_time_recovery.md). 

You can't modify the configuration of an Amazon DocumentDB cluster, or any of its instances, while the cluster is stopped. You also can't add or remove instances from the cluster, or delete the cluster if it still has any associated instances. You must start the cluster before performing any such administrative actions.

Amazon DocumentDB applies any scheduled maintenance to your stopped cluster only after it's started again. After seven days, Amazon DocumentDB automatically starts a stopped cluster so that it doesn't fall too far behind in its maintenance status. When the cluster restarts, you will begin to be charged for the instances in the cluster again.

While a cluster is stopped, Amazon DocumentDB does not perform any automated backups nor does it extend the backup retention period.

# Deleting an Amazon DocumentDB cluster
<a name="db-cluster-delete"></a>

You can delete an Amazon DocumentDB cluster using the AWS Management Console or the AWS CLI. To delete a cluster, the cluster must be in the *available* state and must not have any instances associated with it. If the cluster is stopped, first start the cluster, wait for the cluster to become *available*, and then delete the cluster. For more information, see [Stopping and starting an Amazon DocumentDB cluster](db-cluster-stop-start.md). 

## Deletion protection
<a name="db-cluster-deletion-protection"></a>

To protect your cluster from accidental deletion, you can enable *deletion protection*. Deletion protection is enabled by default when you create a cluster using the console. However, deletion protection is disabled by default if you create a cluster using the AWS CLI.

Amazon DocumentDB enforces deletion protection for a cluster whether you perform the delete operation using the console or the AWS CLI. If deletion protection is enabled, you can't delete a cluster. To delete a cluster that has deletion protection enabled, you must first modify the cluster and disable deletion protection.

When using the console with deletion protection enabled on a cluster, you can't delete the cluster's last instance because doing so also deletes the cluster. You can delete the last instance of a deletion protected cluster using the AWS CLI. However, the cluster itself still exists, and your data is preserved. You can access the data by creating new instances for the cluster. For more information about enabling and disabling deletion protection, see: 
+ [Creating an Amazon DocumentDB cluster](db-cluster-create.md)
+ [Modifying an Amazon DocumentDB cluster](db-cluster-modify.md)

------
#### [ Using the AWS Management Console ]

To delete a cluster using the AWS Management Console, deletion protection must be disabled.

**To determine whether a cluster has deletion protection enabled:**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. Note that in the Clusters navigation box, the **Cluster identifier** column shows both clusters and instances. Instances are listed underneath clusters, similar to the screenshot below.  
![\[Image: the Clusters navigation box showing a list of existing cluster links and their corresponding instance links.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/clusters.png)

1. Choose the cluster's name, and select the **Configuration** tab. In the **Cluster details** section, locate **Deletion protection**. If deletion protection is enabled, modify the cluster to disable deletion protection. For information about modifying a cluster, see [Modifying an Amazon DocumentDB cluster](db-cluster-modify.md). 

   After **Deletion protection** is disabled, you are ready to delete the cluster.

**To delete a cluster:**

1. In the navigation pane, choose **Clusters**. 

1. Determine whether the cluster has any instances by checking the **Cluster identifier** column for instances listed below it. Before you can delete a cluster, you must delete all of its instances. For more information, see [Deleting an Amazon DocumentDB instance](db-instance-delete.md). 

1. Depending on whether your cluster has any instances, do one of the following steps.
   + If the cluster has no instances, select the button to the left of the cluster name and choose **Actions**. From the dropdown menu, choose **Delete**. Complete the **Delete <cluster-name>** dialog box, and then choose **Delete**. 
   + If the cluster has one or more instances, do the following:

     1. In the navigation pane, choose **Clusters**.

     1. Delete each of the cluster's instances by selecting the checkbox to the left of the cluster's name. Select **Actions**, and then choose **Delete**. Complete the **Delete <cluster-name>** dialog box, and then choose **Delete**.

        When you delete the last instance, the cluster will also be deleted. For more information about deleting instances, see [Deleting an Amazon DocumentDB instance](db-instance-delete.md). 

It takes several minutes for the cluster to be deleted. To monitor the status of the cluster, see [Monitoring an Amazon DocumentDB cluster's status](monitoring_docdb-cluster_status.md). 

------
#### [ Using the AWS CLI ]

You cannot delete a cluster that has any instances associated with it. To determine which instances are associated with your cluster, run the `describe-db-clusters` command and delete all of the cluster's instances. Then, if needed, disable deletion protection on your cluster, and finally, delete the cluster.

1. **First, delete all of the cluster's instances.**

   To determine which instances you need to delete, run the following command.

   ```
   aws docdb describe-db-clusters \
       --db-cluster-identifier sample-cluster \
       --query 'DBClusters[*].[DBClusterIdentifier,DBClusterMembers[*].DBInstanceIdentifier]'
   ```

   Output from this operation looks something like the following (JSON format).

   ```
   [
       [
           "sample-cluster",
           [
               "sample-instance-1",
               "sample-instance-2"
           ]
       ]
   ]
   ```

   If the cluster you want to delete has any instances, delete them as shown below.

   ```
   aws docdb delete-db-instance \
       --db-instance-identifier sample-instance
   ```

1. **Second, disable deletion protection.**

   Using the AWS CLI to delete all of a cluster's instances does not delete the cluster. You must also delete the cluster, but you can do this only if deletion protection is disabled.

   To determine whether the cluster has deletion protection enabled, run the following command.
**Tip**  
To see the deletion protection status of all your Amazon DocumentDB clusters, omit the `--db-cluster-identifier` parameter.

   ```
   aws docdb describe-db-clusters \
       --db-cluster-identifier sample-cluster \
       --query 'DBClusters[*].[DBClusterIdentifier,DeletionProtection]'
   ```

   Output from this operation looks something like the following.

   ```
   [
       [
           "sample-cluster",
           "true"
       ]
   ]
   ```

   If the cluster has deletion protection enabled, modify the cluster and disable deletion protection. To disable deletion protection on the cluster, run the following command.

   ```
   aws docdb modify-db-cluster \
       --db-cluster-identifier sample-cluster \
       --no-deletion-protection \
       --apply-immediately
   ```

1. **Finally, delete the cluster.**

   After deletion protection is disabled, you are ready to delete the cluster. To delete a cluster, use the `delete-db-cluster` operation with the following parameters.
   + **--db-cluster-identifier**—Required. The identifier of the cluster that you want to delete.
   + **--final-db-snapshot-identifier**—Optional. If you want a final snapshot, you must include this parameter with a name for the final snapshot. You must include either `--final-db-snapshot-identifier` or `--skip-final-snapshot`.

     Naming constraints:
     + Length is [1—63] letters, numbers, or hyphens.
     + First character must be a letter.
     + Cannot end with a hyphen or contain two consecutive hyphens.
     + Must be unique for all clusters across Amazon RDS, Amazon Neptune, and Amazon DocumentDB per AWS account, per Region.
   + **--skip-final-snapshot**—Optional. Use this parameter only if you don't want to take a final snapshot before deleting your cluster. The default setting is to take a final snapshot. You must include either `--final-db-snapshot-identifier` or `--skip-final-snapshot`.

   The following AWS CLI code deletes the cluster `sample-cluster` with a final snapshot. The operation fails if there are any instances associated with the cluster or if deletion protection is enabled.  
**Example**  

   For Linux, macOS, or Unix:

   ```
   aws docdb delete-db-cluster \
       --db-cluster-identifier sample-cluster \
       --final-db-snapshot-identifier sample-cluster-final-snapshot
   ```

   For Windows:

   ```
   aws docdb delete-db-cluster ^
       --db-cluster-identifier sample-cluster ^
       --final-db-snapshot-identifier sample-cluster-final-snapshot
   ```  
**Example**  

   The following AWS CLI code deletes the cluster `sample-cluster` without taking a final snapshot.

   For Linux, macOS, or Unix:

   ```
   aws docdb delete-db-cluster \
       --db-cluster-identifier sample-cluster \
       --skip-final-snapshot
   ```

   For Windows:

   ```
   aws docdb delete-db-cluster ^
       --db-cluster-identifier sample-cluster ^
       --skip-final-snapshot
   ```

   The output of the `delete-db-cluster` operation is the cluster you are deleting.

   It takes several minutes for the cluster to be deleted. To monitor the status of the cluster, see [Monitoring a cluster's status](monitoring_docdb-cluster_status.md). 

------

# Scaling Amazon DocumentDB clusters
<a name="db-cluster-manage-performance"></a>

Amazon DocumentDB enables you to scale the storage and compute in your clusters based on your needs. This section describes how you can use storage scaling, instance scaling, and read scaling to manage performance and scaling for your Amazon DocumentDB clusters and instances.

**Topics**
+ [

## Storage scaling
](#db-cluster-manage-scaling-storage)
+ [

## Instance scaling
](#db-cluster-manage-scaling-instance)
+ [

## Read scaling
](#db-cluster-manage-scaling-reads)
+ [

## Write scaling
](#db-cluster-manage-scaling-writes)

## Storage scaling
<a name="db-cluster-manage-scaling-storage"></a>

Amazon DocumentDB storage automatically scales with the data in your cluster volume. As your data grows, your cluster volume storage grows in 10 GiB increments, up to 128 TiB.

## Instance scaling
<a name="db-cluster-manage-scaling-instance"></a>

You can scale your Amazon DocumentDB cluster as needed by modifying the instance class for each instance in the cluster. Amazon DocumentDB supports several instance classes that are optimized for Amazon DocumentDB.

For more information, see [Modifying an Amazon DocumentDB instance](db-instance-modify.md). 

## Read scaling
<a name="db-cluster-manage-scaling-reads"></a>

You can achieve read scaling for your Amazon DocumentDB cluster by creating up to 15 Amazon DocumentDB replicas in the cluster. Each Amazon DocumentDB replica returns the same data from the cluster volume with minimal replica lag—usually less than 100 milliseconds after the primary instance has written an update. As your read traffic increases, you can create additional Amazon DocumentDB replicas and connect to them directly to distribute the read load for your cluster. Amazon DocumentDB replicas don't have to be of the same instance class as the primary instance. 

For more information, see [Adding an Amazon DocumentDB instance to a cluster](db-instance-add.md). 

To read scale with Amazon DocumentDB, we recommend that you connect to your cluster as a replica set and distribute reads to replica instances using the built-in read preference capabilities of your driver. For more information, please see [Connecting to Amazon DocumentDB as a replica set](connect-to-replica-set.md).

## Write scaling
<a name="db-cluster-manage-scaling-writes"></a>

You can scale write capacity on your Amazon DocumentDB cluster by increasing the size of your cluster’s primary instance. This section provides two methods for scaling your cluster’s primary instance based on your needs. The first option seeks to minimize application impact but requires more steps to complete. The second option optimizes for simplicity as it has fewer steps, but it comes with the tradeoff of having more potential impact to your application. 

Depending on your application, you can choose what approach below is best for you. For more information about available instance sizes and costs, see the [Amazon DocumentDB Pricing](https://aws.amazon.com/documentdb/pricing/) page.

1. **Optimize for high availability and performance** — If you are connecting to your cluster in [replica set mode](connect-to-replica-set.md) (recommended), you can use the following process to minimize the impact to your application when scaling your primary instance. This method minimizes impact because it keeps your cluster at or above your high availability, and read scaling targets are added to the cluster as instances, instead of being updated in place.

   1. Add one or more replicas of the larger instance type to your cluster (see [Adding an Amazon DocumentDB instance to a cluster](db-instance-add.md)). We recommend all replicas be of the same or larger instance type as the primary. This avoids an unintentional reduction in write performance from failing over to a smaller instance type. For most customers, this means temporarily doubling the number of instances in their cluster, then removing the smaller replicas after scaling is complete.

   1. Set the failover tier on all new replicas to priority zero, ensuring a replica of the smaller instance type has the highest failover priority. For more information, see [Controlling the failover target](failover.md#failover-target_control). 

   1. Initiate a manual failover, which will promote one of the new replicas to be the primary instance. For more information, see [Testing failover](failover.md#failover-testing). 
**Note**  
This will incur \$130 seconds of downtime for your cluster. Please plan accordingly.

   1. Remove all replicas of an instance type smaller than your new primary from the cluster.

   1. Set the failover tier of all instances back to the same priority (usually, this means setting them back to 1).

   As an example, suppose that you have a cluster that currently contains three `r5.large` instances (one primary and two replicas), and you want to scale to an `r5.xlarge` instance type. To do so, you would first add three `r5.xlarge` replica instances to your cluster and then set the failover tier of the new `r5.xlarge` replicas to zero. Next, you would initiate a manual failover (understanding that your application will experience \$130 seconds of downtime). Once the failover is complete, you would remove all three `r5.large` instances from your cluster, leaving the cluster scaled to `r5.xlarge` instances.

   To help optimize costs, Amazon DocumentDB instances are billed in one second increments, with a ten minute minimum charge following a billable status change such as creating, modifying, or deleting an instance. For more information, see [Cost optimization](best_practices.md#best_practices-cost_optimization) in the best practices documentation.

1. **Optimize for simplicity** — This approach optimizes for simplicity. It doesn’t expand and contract the cluster, but it might temporarily reduce your read capacity.

   It is possible that changing the instance class of a replica will result in that instance not serving requests for a brief period of time, from a few seconds to less than 30 seconds. If you are connecting to your cluster in [replica set mode](connect-to-replica-set.md) (recommended), then this would reduce your read capacity by one replica (e.g., to 66% capacity in a 3-node cluster, or 75% capacity in a 4-node cluster, etc.) during the scaling operation.

   1. Scale one of the replica instances in your cluster. For more information, see [Managing instance classes](db-instance-classes.md). 

   1. Wait until the instance is available (see [Monitoring an Amazon DocumentDB instance's status](monitoring_docdb-instance_status.md)). 
**Note**  
This will incur \$130 seconds of downtime for your cluster. Please plan accordingly.

   1. Continue executing steps 1 and 2 until all replicas instances have been scaled, one by one.

   1. Initiate a manual failover. This will promote one of the replicas to be the primary instance. For more information, see [Amazon DocumentDB Failover](failover.md).
**Note**  
This will incur up to 30 seconds of downtime for your cluster, but often takes less time than that. Please plan accordingly.

   1. Scale the former primary (now a replica) instance.

# Cloning a volume for an Amazon DocumentDB cluster
<a name="db-cluster-cloning"></a><a name="cloning"></a>

By using Amazon DocumentDB cloning, you can create a new cluster that uses the same Amazon DocumentDB cluster volume and has the same data as the original. The process is designed to be fast and cost-effective. The new cluster with its associated data volume is known as a *clone*. Creating a clone is faster and more space-efficient than physically copying the data using other techniques, such as restoring a snapshot.

Amazon DocumentDB supports creating an Amazon DocumentDB provisioned clone from a provisioned Amazon DocumentDB cluster. When you create a clone using a different deployment configuration than the source, the clone is created using the latest version of the source's Amazon DocumentDB engine. 

When you create clones from your Amazon DocumentDB clusters, the clones are created in your AWS account—the same account that owns the source Amazon DocumentDB cluster. 

**Topics**
+ [

## Overview of Amazon DocumentDB cloning
](#db-cloning-overview)
+ [

## Limitations of Amazon DocumentDB cloning
](#db-cloning-limitations)
+ [

## How Amazon DocumentDB cloning works
](#db-how-db-cloning-works)
+ [

## Creating an Amazon DocumentDB clone
](#db-creating-db-clone)

## Overview of Amazon DocumentDB cloning
<a name="db-cloning-overview"></a>

Amazon DocumentDB uses a *copy-on-write protocol* to create a clone. This mechanism uses minimal additional space to create an initial clone. When the clone is first created, Amazon DocumentDB keeps a single copy of the data that is used by the source DB cluster and the new (cloned) Amazon DocumentDB cluster. Additional storage is allocated only when changes are made to data (on the Amazon DocumentDB storage volume) by the source Amazon DocumentDB cluster or the Amazon DocumentDB cluster clone. To learn more about the copy-on-write protocol, see [How Amazon DocumentDB cloning works](#db-how-db-cloning-works). 

Amazon DocumentDB cloning is especially useful for quickly setting up test environments using your production data, without risking data corruption. You can use clones for many types of applications, such as the following:
+ Experiment with potential changes (schema changes and parameter group changes, for example) to assess all impacts. 
+ Run workload-intensive operations, such as exporting data or running analytical queries on the clone. 
+ Create a copy of your production DB cluster for development, testing, or other purposes.

You can create more than one clone from the same Amazon DocumentDB cluster. You can also create multiple clones from another clone. 

After creating an Amazon DocumentDB clone, you can configure the Amazon DocumentDB instances differently from the source Amazon DocumentDB cluster. For example, you might not need a clone for development purposes to meet the same high availability requirements as the source production Amazon DocumentDB cluster. In this case, you can configure the clone with a single Amazon DocumentDB instance rather than the multiple DB instances used by the Amazon DocumentDB cluster.

When you finish using the clone for your testing, development, or other purposes, you can delete it.

## Limitations of Amazon DocumentDB cloning
<a name="db-cloning-limitations"></a>

Amazon DocumentDB; cloning currently has the following limitations:
+ You can create as many clones as you want, up to the maximum number of DB clusters allowed in the AWS Region. However, after you create 15 clones, the next clone is a full copy. The cloning operation acts like a point-in-time recovery.
+ You can't create a clone in a different AWS Region from the source Amazon DocumentDB cluster.
+ You can't create a clone from an Amazon DocumentDB cluster that has no DB instances. You can only clone Amazon DocumentDB clusters that have at least one DB instance.
+ You can create a clone in a different virtual private cloud (VPC) than that of the Amazon DocumentDB cluster. If you do, the subnets of the VPCs must map to the same Availability Zones.

## How Amazon DocumentDB cloning works
<a name="db-how-db-cloning-works"></a>

Amazon DocumentDB cloning works at the storage layer of an Amazon DocumentDB cluster. It uses a *copy-on-write* protocol that's both fast and space-efficient in terms of the underlying durable media supporting the Amazon DocumentDB storage volume. You can learn more about Amazon DocumentDB cluster volumes in [Managing Amazon DocumentDB clusters](db-clusters.md). 

**Topics**
+ [

### Understanding the copy-on-write protocol
](#db-copy-on-write-protocol)
+ [

### Deleting a source cluster volume
](#db-deleting-source-cluster-volume)

### Understanding the copy-on-write protocol
<a name="db-copy-on-write-protocol"></a>

An Amazon DocumentDB cluster stores data in pages in the underlying Amazon DocumentDB storage volume. 

For example, in the following diagram you can find an Amazon DocumentDB cluster (A) that has four data pages, 1, 2, 3, and 4. Imagine that a clone, B, is created from the Amazon DocumentDB cluster. When the clone is created, no data is copied. Rather, the clone points to the same set of pages as the source Amazon DocumentDB cluster.

![\[Amazon DocumentDB cluster volume with 4 pages for source cluster, A, and clone, B\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cloning-copy-on-write-protocol-1.png)


When the clone is created, no additional storage is usually needed. The copy-on-write protocol uses the same segment on the physical storage media as the source segment. Additional storage is required only if the capacity of the source segment isn't sufficient for the entire clone segment. If that's the case, the source segment is copied to another physical device. 

In the following diagrams, you can find an example of the copy-on-write protocol in action using the same cluster A and its clone, B, as shown preceding. Let's say that you make a change to your Amazon DocumentDB cluster (A) that results in a change to data held on page 1. Instead of writing to the original page 1, Amazon DocumentDB creates a new page 1[A]. The Amazon DocumentDB cluster volume for cluster (A) now points to page 1[A], 2, 3, and 4, while the clone (B) still references the original pages. 

![\[Amazon DocumentDB source DB cluster volume and its clone, both with changes.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cloning-copy-on-write-protocol-2.png)


On the clone, a change is made to page 4 on the storage volume. Instead of writing to the original page 4, Amazon DocumentDB creates a new page, 4[B]. The clone now points to pages 1, 2, 3, and to page 4[B], while the cluster (A) continues pointing to 1[A], 2, 3, and 4. 

![\[Amazon DocumentDB source DB cluster volume and its clone, both with changes.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cloning-copy-on-write-protocol-3.png)


As more changes occur over time in both the source Amazon DocumentDB cluster volume and the clone, more storage is needed to capture and store the changes. 

### Deleting a source cluster volume
<a name="db-deleting-source-cluster-volume"></a>

When you delete a source cluster volume that has one or more clones associated with it, the clones aren't affected. The clones continue to point to the pages that were previously owned by the source cluster volume. 

## Creating an Amazon DocumentDB clone
<a name="db-creating-db-clone"></a>

You can create a clone in the same AWS account as the source Amazon DocumentDB cluster. To do so, you can use the AWS Management Console or the AWS CLI and the procedures following.

By using Amazon DocumentDB cloning, you can create a provisioned Amazon DocumentDB cluster clone from a provisioned Amazon DocumentDB cluster.

------
#### [ Using the AWS Management Console ]

The following procedure describes how to clone an Amazon DocumentDB cluster using the AWS Management Console.

Creating a clone using the AWS Management Console results in an Amazon DocumentDB cluster with one Amazon DocumentDB instance.

 These instructions apply for DB clusters owned by the same AWS account that is creating the clone. The DB cluster must be owned by the same AWS account as cross-account cloning is not supported in Amazon DocumentDB. 

**To create a clone of a DB cluster owned by your AWS account using the AWS Management Console**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**. 

1. Choose your Amazon DocumentDB cluster from the list, and for **Actions**, choose **Create clone**.  
![\[Creating a clone starts by selecting your Amazon DocumentDB cluster.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cloning-create-clone-1.png)

   The Create clone page opens, where you can configure a **Cluster identifier** and an **Instance class**, and other options for the Amazon DocumentDB cluster clone. 

1. In the **Settings** section, do the following:

   1. For **Cluster identifier**, enter the name that you want to give to your cloned Amazon DocumentDB cluster.

   1. For **Instance configuration**, select an appropriate **Instance class** for your cloned Amazon DocumentDB cluster.  
![\[Creating a clone starts by selecting your Amazon DocumentDB cluster and specifying a DB instance size.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cloning-create-clone-2.png)

   1.  For **Network settings**, choose a **Subnet group** for your use case and the associated VPC security groups. 

   1.  For **Encryption-at-rest**, if the source cluster (the cluster that is being cloned) has encryption enabled, the cloned cluster must also have encryption enabled. If this scenario is true, then the **Enable encryption** options are grayed out (disabled) but with the **Enable encryption** choice selected. Conversely, if the source cluster does not have encryption enabled, the **Enable encryption** options are available and you can choose to enable or disable encryption.   
![\[Specify network and encryption settings for your Amazon DocumentDB cluster clone.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cloning-create-clone-3-nw-encryption.png)

   1. Complete the new cluster clone configuration by selecting the type of logs to export (optional), entering a specific port used to connect to the cluster, and enabling protection from accidentally deleting the cluster (enabled by default).  
![\[Complete the new clone configuration by optionally selecting the type of logs to export, a specific port used to connect to the cluster, and protection form accidentally deleting the cluster.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cloning-create-clone-4-log-options-del-prot-b.png)

   1. Finish entering all settings for your Amazon DocumentDB cluster clone. To learn more about Amazon DocumentDB cluster and instance settings, see [Managing Amazon DocumentDB clusters](db-clusters.md). 

1. Choose **Create clone** to launch the Amazon DocumentDB clone of your chosen Amazon DocumentDB cluster.

When the clone is created, it's listed with your other Amazon DocumentDB clusters in the console **Databases** section and displays its current state. Your clone is ready to use when its state is **Available**.

------
#### [ Using the AWS CLI ]

Using the AWS CLI for cloning your Amazon DocumentDB cluster involves a couple of steps. 

The `restore-db-cluster-to-point-in-time` AWS CLI command that you use results in an empty Amazon DocumentDB cluster with 0 Amazon DocumentDB instances. That is, the command restores only the Amazon DocumentDB cluster, not the DB instances for that cluster. You do that separately after the clone is available. The two steps in the process are as follows: 

1. Create the clone by using the [restore-db-cluster-to-point-in-time](https://docs.aws.amazon.com/cli/latest/reference/rds/restore-db-cluster-to-point-in-time.html) CLI command. The parameters that you use with this command control the capacity type and other details of the empty Amazon DocumentDB cluster (clone) being created. 

1. Create the Amazon DocumentDB instance for the clone by using the [create-db-instance](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html) CLI command to recreate the Amazon DocumentDB instance in the restored Amazon DocumentDB cluster. 

The commands following assume that the AWS CLI is set up with your AWS Region as the default. This approach saves you from passing the `--region` name in each of the commands. For more information, see [Configuring the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html). You can also specify the `--region` in each of the CLI commands that follow. 

**Topics**

**Creating the clone**

The specific parameters that you pass to the `[restore-db-cluster-to-point-in-time](https://docs.aws.amazon.com/cli/latest/reference/rds/restore-db-cluster-to-point-in-time.html)` CLI command vary. What you pass depends on the type of clone that you want to create.

Use the following procedure to create a provisioned Amazon DocumentDB clone from a provisioned Amazon DocumentDB cluster. 

**To create a clone of the same engine mode as the source Amazon DocumentDB cluster**
+ Use the `[restore-db-cluster-to-point-in-time](https://docs.aws.amazon.com/cli/latest/reference/rds/restore-db-cluster-to-point-in-time.html)` CLI command and specify values for the following parameters:
  + `--db-cluster-identifier` – Choose a meaningful name for your clone. You name the clone when you use the [restore-db-cluster-to-point-in-time](https://docs.aws.amazon.com/cli/latest/reference/rds/restore-db-cluster-to-point-in-time.html) CLI command. 
  + `--restore-type` – Use `copy-on-write` to create a clone of the source DB cluster. Without this parameter, the `restore-db-cluster-to-point-in-time` restores the Amazon DocumentDB cluster rather than creating a clone. Default for `restore-type` is `full-copy`.
  + `--source-db-cluster-identifier` – Use the name of the source Amazon DocumentDB cluster that you want to clone.
  + `--use-latest-restorable-time` – This value points to the latest restorable volume data for the clone. This parameter is required for `restore-type copy-on-write`, however, you can not use the `restore-to-time parameter` with it.

The following example creates a clone named `my-clone` from a cluster named `my-source-cluster`.

For Linux, macOS, or Unix:

```
aws docdb restore-db-cluster-to-point-in-time \
    --source-db-cluster-identifier my-source-cluster \
    --db-cluster-identifier my-clone \
    --restore-type copy-on-write \
    --use-latest-restorable-time
```

For Windows:

```
aws docdb restore-db-cluster-to-point-in-time ^
    --source-db-cluster-identifier my-source-cluster ^
    --db-cluster-identifier my-clone ^
    --restore-type copy-on-write ^
    --use-latest-restorable-time
```

The command returns the JSON object containing details of the clone. Check to make sure that your cloned DB cluster is available before trying to create the DB instance for your clone. For more information, see Checking the status and getting clone details below: 

**Checking the status and getting clone details**

You can use the following command to check the status of your newly created empty DB cluster.

```
$ aws docdb describe-db-clusters --db-cluster-identifier my-clone --query '*[].[Status]' --output text
```

Or you can obtain the status and the other values that you need to create the DB instance for your clone by using the following AWS CLI query: 

For Linux, macOS, or Unix:

```
aws docdb describe-db-clusters --db-cluster-identifier my-clone \
  --query '*[].{Status:Status,Engine:Engine,EngineVersion:EngineVersion}'
```

For Windows:

```
aws docdb describe-db-clusters --db-cluster-identifier my-clone ^
  --query "*[].{Status:Status,Engine:Engine,EngineVersion:EngineVersion}"
```

This query returns output similar to the following.

```
[
  {
        "Status": "available",
        "Engine": "docdb",
        "EngineVersion": "4.0.0",
    }
]
```

**Creating the Amazon DocumentDB instance for your clone**

Use the [create-db-instance](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html) CLI command to create the DB instance for your clone. 

The `--db-instance-class` parameter is used for provisioned Amazon DocumentDB clusters only.

For Linux, macOS, or Unix:

```
aws docdb create-db-instance \
    --db-instance-identifier my-new-db \
    --db-cluster-identifier my-clone \
    --db-instance-class  db.r5.4xlarge \
    --engine docdb
```

For Windows:

```
aws docdb create-db-instance ^
    --db-instance-identifier my-new-db ^
    --db-cluster-identifier my-clone ^
    --db-instance-class  db.r5.4xlarge ^
    --engine docdb
```

**Parameters to use for cloning**

The following table summarizes the various parameters used with `restore-db-cluster-to-point-in-time` to clone Amazon DocumentDB clusters.


| Parameter | Description | 
| --- | --- | 
|  --source-db-cluster-identifier | Use the name of the source Amazon DocumentDB cluster that you want to clone. | 
|  --db-cluster-identifier | Choose a meaningful name for your clone. You name your clone with the ` restore-db-cluster-to-point-in-time` command. Then you pass this name to the `create-db-instance` command.  | 
|  --restore-type | Specify `copy-on-write` as the `--restore-type` to create a clone of the source DB cluster rather than restoring the source Amazon DocumentDB cluster.  | 
|  --use-latest-restorable-time | This value points to the latest restorable volume data for the clone. | 

------

# Understanding Amazon DocumentDB cluster fault tolerance
<a name="db-cluster-fault-tolerance"></a>

Amazon DocumentDB clusters are fault tolerant by design. Each cluster's volume spans multiple Availability Zones in a single AWS Region, and each Availability Zone contains a copy of the cluster's volume data. This functionality means that your cluster can tolerate an Availability Zone failure without any loss of data and only a brief interruption of service. 

If the primary instance in a cluster fails, Amazon DocumentDB automatically performs a failover to a new primary instance in one of two ways:
+ By promoting an existing Amazon DocumentDB replica to the new primary instance chosen based on the Promotion Tier setting of each replica, and then creating a replacement for the former primary. A failover to the replica instance typically takes less than 30 seconds. Read and write operations may experience brief interruption during this period. To increase the availability of your cluster, we recommend that you create at least one or more Amazon DocumentDB replicas in two or more different Availability Zones.
+ By creating a new primary instance. This only happens if you do not have a replica instance in your cluster and can take a few minutes to complete.

If the cluster has one or more Amazon DocumentDB replicas, an Amazon DocumentDB replica is promoted to the primary instance during a failure event. A failure event results in a brief interruption, during which read and write operations fail with an exception. However, service is typically restored in less than 120 seconds, and often less than 60 seconds. To increase the availability of your cluster, we recommend that you create at least one or more Amazon DocumentDB replicas in two or more different Availability Zones. 

You can customize the order in which your Amazon DocumentDB replicas are promoted to the primary instance after a failure by assigning each replica a priority. Priorities range from 0 for the highest priority to 15 for the lowest priority. If the primary instance fails, the Amazon DocumentDB replica with the highest priority is promoted to the new primary instance. You can modify the priority of an Amazon DocumentDB replica at any time. Modifying the priority doesn't trigger a failover. You can use the `modify-db-instance` operation with the `--promotion-tier` parameter. For more information about customizing the failover priority of an instance, see [Amazon DocumentDB Failover](failover.md).

More than one Amazon DocumentDB replica can share the same priority, resulting in promotion tiers. If two or more Amazon DocumentDB replicas share the same priority, then the replica that is largest in size is promoted to primary. If two or more Amazon DocumentDB replicas share the same priority and size, an arbitrary replica in the same promotion tier is promoted. 

If the cluster doesn't contain any Amazon DocumentDB replicas, the primary instance is re-created during a failure event. A failure event results in an interruption, during which read and write operations fail with an exception. Service is restored when the new primary instance is created, which typically takes less than 10 minutes. Promoting an Amazon DocumentDB replica to the primary instance is much faster than creating a new primary instance. 

# Managing Amazon DocumentDB instances
<a name="db-instances"></a>

The following topics provide information to help you manage your Amazon DocumentDB instances. They include details about instance classes and statuses, and how to create, delete, and modify an instance.

**Topics**
+ [

## Determining an instance's status
](#db-instance-status)
+ [Instance lifecycle](db-instance-life-cycle.md)
+ [

# Managing instance classes
](db-instance-classes.md)
+ [

# NVMe-backed instances
](db-instance-nvme.md)

## Determining an instance's status
<a name="db-instance-status"></a>

To see the valid instance statuses, their meaning, and how to determine the status of your instances, see [Monitoring an Amazon DocumentDB instance's status](monitoring_docdb-instance_status.md).

# Amazon DocumentDB instance lifecycle
<a name="db-instance-life-cycle"></a>

The lifecycle of an Amazon DocumentDB instance includes creating, modifying, maintaining and upgrading, performing backups and restores, rebooting, and deleting the instance. This section provides information about how to complete these processes. 

**Topics**
+ [Adding an instance](db-instance-add.md)
+ [Describing instances](db-instance-view-details.md)
+ [Modifying an instance](db-instance-modify.md)
+ [Rebooting an instance](db-instance-reboot.md)
+ [Deleting an instance](db-instance-delete.md)

You can create a new Amazon DocumentDB instance using the AWS Management Console or the AWS CLI. To add an instance to a cluster, the cluster must be in an *available* state. You cannot add an instance to a cluster that is stopped. If the cluster is stopped, first start the cluster, wait for the cluster to become *available*, and then add an instance. For more information, see [Stopping and starting an Amazon DocumentDB cluster](db-cluster-stop-start.md). 

**Note**  
If you create an Amazon DocumentDB cluster using the console, an instance is automatically created for you at the same time. If you want to create additional instances, use one of the following procedures.

# Adding an Amazon DocumentDB instance to a cluster
<a name="db-instance-add"></a>

------
#### [ Using the AWS Management Console ]

Use the following procedure to create an instance for your cluster using the Amazon DocumentDB console.

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. To choose the cluster that you want to add an instance to, select the button to the left of the cluster's name.

1. Choose **Actions**, and then choose **Add instances**.

1. In the **Add instance to: <cluster-name>** page, repeat the following steps for each instance that you want to add to the cluster. You can have up to 15.

   1. **Instance identifier**— You can either enter a unique identifier for this instance or allow Amazon DocumentDB to provide the instance identifier based on the cluster identifier.

      Instance naming constraints:
      + Length is [1—63] letters, numbers, or hyphens.
      + First character must be a letter.
      + Cannot end with a hyphen or contain two consecutive hyphens.
      + Must be unique for all instances across Amazon RDS, Neptune, and Amazon DocumentDB per AWS account, per Region.

   1. **Instance class** — From the drop-down list, choose the instance type you want for this instance.

   1. **Promotion tier** — From the drop-down list, choose the promotion tier for your instance or choose *No preference* to allow Amazon DocumentDB to set the promotion tier for your instance. Lower numbers mean higher priority. For more information, see [Controlling the failover target](failover.md#failover-target_control).

   1. To add more instances, choose **Add additional instances** and repeat steps a, b, and c.

1. Finish the operation.
   + To add the instances to your cluster, choose **Create**.
   + To cancel the operation, choose **Cancel**.

It takes several minutes to create an instance. You can use the console or AWS CLI to view the instance's status. For more information, see [Monitoring an instance's status](monitoring_docdb-instance_status.md). 

------
#### [ Using the AWS CLI ]

Use the `create-db-instance` AWS CLI operation with the following parameters to create the primary instance for your cluster.
+ **--db-instance-class** — Required. The compute and memory capacity of the instance, for example, `db.m4.large`. Not all instance classes are available in all AWS Regions.
+ **--db-instance-identifier** — Required. A string that identifies the instance.

  Instance Naming Constraints:
  + Length is [1—63] letters, numbers, or hyphens.
  + First character must be a letter.
  + Cannot end with a hyphen or contain two consecutive hyphens.
  + Must be unique for all instances across Amazon RDS, Neptune, and Amazon DocumentDB per AWS account, per Region.
+ **--engine** — Required. Must be `docdb`.
+ **--availability-zone** — Optional. The Availability Zone that you want this instance to be created in. Use this parameter to locate your instances in different Availability Zones to increase fault tolerance. For more information, see [Amazon DocumentDB High availability and replication](replication.md). 
+ **--promotion-tier** — Optional. The failover priority tier for this instance. Must be between 0 and 15 with lower numbers being higher priority. For more information, see [Controlling the failover target](failover.md#failover-target_control). 

1. **First, determine what Availability Zones you can create your instance in. **

   If you want to specify the Availability Zone before you create your instance, run the following command to determine which Availability Zones are available for your Amazon DocumentDB cluster.

   For Linux, macOS, or Unix:

   ```
   aws docdb describe-db-clusters \
          --query 'DBClusters[*].[DBClusterIdentifier,AvailabilityZones[*]]'
   ```

   For Windows:

   ```
   aws docdb describe-db-clusters ^
          --query 'DBClusters[*].[DBClusterIdentifier,AvailabilityZones[*]]'
   ```

   Output from this operation looks something like the following.

   ```
   [
       [
           "sample-cluster",
           [
               "us-east-1c",
               "us-east-1b",
               "us-east-1a"
           ]
       ]
   ]
   ```

1. **Second, determine what instance classes you can create in your Region. **

   To determine which instance classes are available to you in your Region, run the following command. From the output, choose an instance class for the instance you want to add to your Amazon DocumentDB cluster. 

   For Linux, macOS, or Unix:

   ```
   aws docdb describe-orderable-db-instance-options \
           --engine docdb \
           --query 'OrderableDBInstanceOptions[*].DBInstanceClass'
   ```

   For Windows:

   ```
   aws docdb describe-orderable-db-instance-options ^
           --engine docdb ^
           --query 'OrderableDBInstanceOptions[*].DBInstanceClass'
   ```

   Output from this operation looks something like the following.

   ```
   [
       "db.r5.16xlarge",
       "db.r5.2xlarge",
       "db.r5.4xlarge",
       "db.r5.8xlarge",
       "db.r5.large",
       "db.r5.xlarge"
   ]
   ```

1. **Finally, add an instance to your Amazon DocumentDB cluster.**

   To add an instance to your Amazon DocumentDB cluster, run the following command..

   For Linux, macOS, or Unix:

   ```
   aws docdb create-db-instance \
          --db-cluster-identifier sample-cluster \
          --db-instance-identifier sample-instance-2 \
          --availability-zone us-east-1b \
          --promotion-tier 2 \
          --db-instance-class db.r5.xlarge \
          --engine docdb
   ```

   For Windows:

   ```
   aws docdb create-db-instance ^
          --db-cluster-identifier sample-cluster ^
          --db-instance-identifier sample-instance-2 ^
          --availability-zone us-east-1b ^
          --promotion-tier 2 ^
          --db-instance-class db.r5.xlarge ^
          --engine docdb
   ```

   Output from this operation looks something like the following.

   ```
   {
       "DBInstance": {
           "DBInstanceIdentifier": "sample-instance-2",
           "DBInstanceClass": "db.r5.xlarge",
           "Engine": "docdb",
           "DBInstanceStatus": "creating",
           "PreferredBackupWindow": "02:00-02:30",
           "BackupRetentionPeriod": 1,
           "VpcSecurityGroups": [
               {
                   "VpcSecurityGroupId": "sg-abcd0123",
                   "Status": "active"
               }
           ],
           "AvailabilityZone": "us-east-1b",
           "DBSubnetGroup": {
               "DBSubnetGroupName": "default",
               "DBSubnetGroupDescription": "default",
               "VpcId": "vpc-6242c31a",
               "SubnetGroupStatus": "Complete",
               "Subnets": [
                   {
                       "SubnetIdentifier": "subnet-abcd0123",
                       "SubnetAvailabilityZone": {
                           "Name": "us-west-2a"
                       },
                       "SubnetStatus": "Active"
                   },
                   {
                       "SubnetIdentifier": "subnet-wxyz0123",
                       "SubnetAvailabilityZone": {
                           "Name": "us-west-2b"
                       },
                       "SubnetStatus": "Active"
                   }
               ]
           },
           "PreferredMaintenanceWindow": "sun:11:35-sun:12:05",
           "PendingModifiedValues": {},
           "EngineVersion": "3.6.0",
           "AutoMinorVersionUpgrade": true,
           "PubliclyAccessible": false,
           "DBClusterIdentifier": "sample-cluster",
           "StorageEncrypted": true,
           "KmsKeyId": "arn:aws:kms:us-east-1:<accountID>:key/sample-key",
           "DbiResourceId": "db-ABCDEFGHIJKLMNOPQRSTUVWXYZ",
           "CACertificateIdentifier": "rds-ca-2019",
           "PromotionTier": 2,
           "DBInstanceArn": "arn:aws:rds:us-east-1:<accountID>:db:sample-instance-2"
       }
   }
   ```

It takes several minutes to create the instance. You can use the console or AWS CLI to view the instance's status. For more information, see [Monitoring an Amazon DocumentDB instance's status](monitoring_docdb-instance_status.md). 

------

# Describing Amazon DocumentDB instances
<a name="db-instance-view-details"></a>

You can use either the Amazon DocumentDB Management Console or the AWS CLI to see details such as connection endpoints, security groups VPCs, certificate authority, and parameter groups pertaining to your Amazon DocumentDB instances.

------
#### [ Using the AWS Management Console ]

To view the details of your instances using the AWS Management Console, follow the steps below.

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters **.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the Clusters navigation box, you’ll see the column **Cluster Identifier**. Your instances are listed under clusters, similar to the screenshot below.  
![\[Clusters table showing list of clusters under Cluster identifier column, with instances nested inside clusters.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/choose-clusters.png)

1. In the list of instances, choose the name of the instance that you want to see its details. The information about the instance is organized into the following groupings:
   + **Summary**—General information about the instance, including the engine version, class, status, and any pending maintenance.
   + **Connectivity & Security** —The **Connect** section lists the connection endpoints to connect to this instance with the mongo shell or with an application. The **Security Groups** section lists the security groups associated with this instance and their VPC ID and descriptions.
   + **Configuration**—The **Details** section lists the configurations and status of the instance, including the instance's Amazon Resource Name (ARN), endpoint, role, class, and certificate authority. It also lists the instance's security and network settings, and backup information. The **Cluster details** section lists the details of the cluster that this instance belongs to. The **Cluster instances** section lists all the instances that belong to your cluster with each instance's role and cluster parameter group status.
**Note**  
You can modify the cluster associated with your instance by selecting **Modify** next to the **Cluster details** header. For more information, see [Modifying an Amazon DocumentDB cluster](db-cluster-modify.md). 
   + **Monitoring**—The CloudWatch Logs metrics for this instance. For more information, see [Monitoring Amazon DocumentDB with CloudWatch](cloud_watch.md). 
   + **Events & tags** —The **Recent events** section lists the recent events for this instance. Amazon DocumentDB keeps a record of events that relate to your clusters, instances, snapshots, security groups, and cluster parameter groups. This information includes the date, time, and message associated with each event. The **Tags** section lists the tags attached to this cluster. For more information, see [Tagging Amazon DocumentDB resources](tagging.md).

------
#### [ Using the AWS CLI ]

To view the details of your Amazon DocumentDB instances using the AWS CLI, use the `describe-db-clusters` command as shown in the examples below. For more information, see [https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DescribeDBInstances.html](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DescribeDBInstances.html) in the *Amazon DocumentDB Resource Management API Reference*. 

**Note**  
For certain management features such as cluster and instance lifecycle management, Amazon DocumentDB leverages operational technology that is shared with Amazon RDS. The `filterName=engine,Values=docdb` filter parameter returns only Amazon DocumentDB clusters.

1. **List all Amazon DocumentDB instances.**

   The following AWS CLI code lists the details for all Amazon DocumentDB instances in a region.

   For Linux, macOS, or Unix:

   ```
   aws docdb describe-db-instances \
       --filter Name=engine,Values=docdb
   ```

   For Windows:

   ```
   aws docdb describe-db-instances \
       --filter Name=engine,Values=docdb
   ```

1. **List all details for a specified Amazon DocumentDB instance**

   The following code lists the details for `sample-cluster-instance`. Including the `--db-instance-identifier` parameter with the name of an instance restricts the output to information on that particular instance.

   For Linux, macOS, or Unix:

   ```
   aws docdb describe-db-instances \
       --db-instance-identifier sample-cluster-instance
   ```

   For Windows:

   ```
   aws docdb describe-db-instances \
       --db-instance-identifier sample-cluster-instance
   ```

   Output from this operation looks like the following.

   ```
   {
       "DBInstances": [
           {
               "DbiResourceId": "db-BJKKB54PIDV5QFKGVRX5T3S6GM",
               "DBInstanceArn": "arn:aws:rds:us-east-1:012345678901:db:sample-cluster-instance-00",
               "VpcSecurityGroups": [
                   {
                       "VpcSecurityGroupId": "sg-77186e0d",
                       "Status": "active"
                   }
               ],
               "DBInstanceClass": "db.r5.large",
               "DBInstanceStatus": "creating",
               "AutoMinorVersionUpgrade": true,
               "PreferredMaintenanceWindow": "fri:09:32-fri:10:02",
               "BackupRetentionPeriod": 1,
               "StorageEncrypted": true,
               "DBClusterIdentifier": "sample-cluster",
               "EngineVersion": "3.6.0",
               "AvailabilityZone": "us-east-1a",
               "Engine": "docdb",
               "PromotionTier": 2,
               "DBInstanceIdentifier": "sample-cluster-instance",
               "PreferredBackupWindow": "00:00-00:30",
               "PubliclyAccessible": false,
               "DBSubnetGroup": {
                   "DBSubnetGroupName": "default",
                   "Subnets": [
                       {
                           "SubnetIdentifier": "subnet-4e26d263",
                           "SubnetAvailabilityZone": {
                               "Name": "us-east-1a"
                           },
                           "SubnetStatus": "Active"
                       },
                       {
                           "SubnetIdentifier": "subnet-afc329f4",
                           "SubnetAvailabilityZone": {
                               "Name": "us-east-1c"
                           },
                           "SubnetStatus": "Active"
                       },
                       {
                           "SubnetIdentifier": "subnet-b3806e8f",
                           "SubnetAvailabilityZone": {
                               "Name": "us-east-1e"
                           },
                           "SubnetStatus": "Active"
                       },
                       {
                           "SubnetIdentifier": "subnet-53ab3636",
                           "SubnetAvailabilityZone": {
                               "Name": "us-east-1d"
                           },
                           "SubnetStatus": "Active"
                       },
                       {
                           "SubnetIdentifier": "subnet-991cb8d0",
                           "SubnetAvailabilityZone": {
                               "Name": "us-east-1b"
                           },
                           "SubnetStatus": "Active"
                       },
                       {
                           "SubnetIdentifier": "subnet-29ab1025",
                           "SubnetAvailabilityZone": {
                               "Name": "us-east-1f"
                           },
                           "SubnetStatus": "Active"
                       }
                   ],
                   "VpcId": "vpc-91280df6",
                   "DBSubnetGroupDescription": "default",
                   "SubnetGroupStatus": "Complete"
               },
               "PendingModifiedValues": {},
               "KmsKeyId": "arn:aws:kms:us-east-1:012345678901:key/0961325d-a50b-44d4-b6a0-a177d5ff730b"
           }
       ]
   }
   ```

------

# Modifying an Amazon DocumentDB instance
<a name="db-instance-modify"></a>

You can modify your Amazon DocumentDB instance using either the AWS Management Console or the AWS CLI. To modify an instance, the instance must be in the *available* state. You cannot modify an instance that is stopped. If the cluster is stopped, first start the cluster, wait for the instance to become *available*, and then make the desired modifications. For more information, see [Stopping and starting an Amazon DocumentDB cluster](db-cluster-stop-start.md). 

------
#### [ Using the AWS Management Console ]

To modify a specific Amazon DocumentDB instance using the console, complete the following steps.

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters **.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the Clusters navigation box, you’ll see the column **Cluster Identifier**. Your instances are listed under clusters, similar to the screenshot below.  
![\[Clusters table showing list of clusters under Cluster identifier column, with instances nested inside clusters.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/choose-clusters.png)

1. Check the box to the left of the instance you wish to modify.

1. Choose **Actions**, and then choose **Modify**.

1. In the **Modify instance: <instance-name>** pane, make the changes that you want. You can make the following changes:
   + **Instance specifications** — The instance identifier and class. Instance identifier naming constraints:
     + **Instance identifier** — Enter a name that is unique for all instances owned by your AWS account in the current region. The instance identifier must contain [1—63] alphanumeric characters or hyphens, have a letter as the first character, and cannot end with a hyphen or contain two consecutive hyphens.
     + **Instance class** — From the drop-down menu, select an instance class for your Amazon DocumentDB instance. For more information, see [Managing instance classes](db-instance-classes.md).
   + **Certificate authority** — Server certificate for this instance. For more information, see [Updating your Amazon DocumentDB TLS certificates](ca_cert_rotation.md). 
   + **Failover** — During failover, the instance with the highest promotion tier will be promoted to primary. For more information, see [Amazon DocumentDB Failover](failover.md). 
   + **Maintenance** — The maintenance window in which pending modifications or patches are applied to instances in the cluster.

1. When you have finished, choose **Continue** to see a summary of your changes.

1. After verifying your changes, you can apply them immediately or during the next maintenance window under **Scheduling of modifications**. Choose **Modify instance** to save your changes. Alternatively, you can choose **Cancel** to discard your changes.

It takes a few minutes for your changes to be applied. You can use the instance only when its status is *available*. You can monitor the instance's status using the console or AWS CLI. For more information, see [Monitoring an Amazon DocumentDB instance's status](monitoring_docdb-instance_status.md). 

------
#### [ Using the AWS CLI ]

To modify a specific Amazon DocumentDB instance using the AWS CLI, use the `modify-db-instance` with the following parameters. For more information, see [ ModifyDBInstance](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_ModifyDBInstance.html). The following code modifies the instance class to `db.r5.large` for the instance `sample-instance`.

**Parameters**
+ **--db-instance-identifier** — Required. The identifier for the instance to be modified.
+ **--db-instance-class** — Optional. The new compute and memory capacity of the instance; for example, `db.r5.large`. Not all instance classes are available in all AWS Regions. If you modify the instance class, an outage occurs during the change. The change is applied during the next maintenance window, unless `ApplyImmediately` is specified as true for this request.
+ **--apply-immediately** or **--no-apply-immediately** — Optional. Specifies whether this modification should be applied immediately or wait until the next maintenance window. If this parameter is omitted, the modification is performed during the next maintenance window.

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb modify-db-instance \
       --db-instance-identifier sample-instance \
       --db-instance-class db.r5.large \
       --apply-immediately
```
For Windows:  

```
aws docdb modify-db-instance ^
       --db-instance-identifier sample-instance ^
       --db-instance-class db.r5.large ^
       --apply-immediately
```
Output from this operation looks something like the following.  

```
{
    "DBInstances": [
        {
            "DBInstanceIdentifier": "sample-instance-1",
            "DBInstanceClass": "db.r5.large",
            "Engine": "docdb",
            "DBInstanceStatus": "modifying",
            "Endpoint": {                     
                "Address": "sample-instance-1.node.us-east-1.docdb.amazonaws.com",
                "Port": 27017,   
                "HostedZoneId": "ABCDEFGHIJKLM"
            },
            "InstanceCreateTime": "2020-01-10T22:18:55.921Z",
            "PreferredBackupWindow": "02:00-02:30",
            "BackupRetentionPeriod": 1,
            "VpcSecurityGroups": [
                {                             
                    "VpcSecurityGroupId": "sg-abcd0123",
                    "Status": "active"
                }
            ],
            "AvailabilityZone": "us-east-1a",
            "DBSubnetGroup": {
                "DBSubnetGroupName": "default",
                "DBSubnetGroupDescription": "default",
                "VpcId": "vpc-abcd0123",
                "SubnetGroupStatus": "Complete",
                "Subnets": [
                    {
                        "SubnetIdentifier": "subnet-abcd0123",
                        "SubnetAvailabilityZone": {
                            "Name": "us-east-1a"
                        },
                        "SubnetStatus": "Active"
                    },
                    {
                        "SubnetIdentifier": "subnet-abcd0123",
                        "SubnetAvailabilityZone": {
                            "Name": "us-east-1b"
                        },
                        "SubnetStatus": "Active"
                    }
                ]
            },
            "PreferredMaintenanceWindow": "sun:10:57-sun:11:27",
            "PendingModifiedValues": {
                "DBInstanceClass": "db.r5.large"
            },
            "EngineVersion": "3.6.0",
            "AutoMinorVersionUpgrade": true,
            "PubliclyAccessible": false,
            "DBClusterIdentifier": "sample-cluster",
            "StorageEncrypted": true,
            "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
            "DbiResourceId": "db-ABCDEFGHIJKLMNOPQRSTUVWXYZ",
            "CACertificateIdentifier": "rds-ca-2019",
            "PromotionTier": 1,                     
            "DBInstanceArn": "arn:aws:rds:us-east-1:123456789012:db:sample-instance-1",
            "EnabledCloudwatchLogsExports": [
                "profiler"
            ]
        }
    ]
}
```

It takes a few minutes for your modifications to be applied. You can use the instance only when its status is *available*. You can monitor the instance's status using the AWS Management Console or AWS CLI. For more information, see [Monitoring an Amazon DocumentDB instance's status](monitoring_docdb-instance_status.md). 

------

# Rebooting an Amazon DocumentDB instance
<a name="db-instance-reboot"></a>

Occasionally, you might need to reboot your Amazon DocumentDB instance, usually for maintenance reasons. If you make certain changes, such as changing the cluster parameter group that is associated with a cluster, you must reboot the instances in the cluster for the changes to take effect. You can reboot a specified instance using the AWS Management Console or the AWS CLI.

Rebooting an instance restarts the database engine service. Rebooting results in a momentary outage, during which the instance status is set to `rebooting`. An Amazon DocumentDB event is created when the reboot is completed.

Rebooting an instance doesn't result in a failover. To failover an Amazon DocumentDB cluster, use the AWS Management Console or the AWS CLI operation `failover-db-cluster`. For more information, see [Amazon DocumentDB Failover](failover.md). 

You can't reboot your instance if it isn't in the *available* state. Your database can be unavailable for several reasons, such as a previously requested modification, or a maintenance-window action. For more information on instance states, see [Monitoring an Amazon DocumentDB instance's status](monitoring_docdb-instance_status.md). 

------
#### [ Using the AWS Management Console ]

The following procedure reboots an instance that you specify using the console.

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters **.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the Clusters navigation box, you’ll see the column **Cluster Identifier**. Your instances are listed under clusters, similar to the screenshot below.  
![\[Clusters table showing list of clusters under Cluster identifier column, with instances nested inside clusters.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/choose-clusters.png)

1. Check the box to the left of the instance you wish to reboot.

1. Choose **Actions**, choose **Reboot**, and then choose **Reboot** to confirm your reboot.

It takes a few minutes for your instance to reboot. You can use the instance only when its status is *available*. You can monitor the instance's status using the console or the AWS CLI. For more information, see [Monitoring an Amazon DocumentDB instance's status](monitoring_docdb-instance_status.md). 

------
#### [ Using the AWS CLI ]

To reboot an Amazon DocumentDB instance, use the `reboot-db-instance` operation with the `--db-instance-identifier` parameter. This parameter specifies the identifier for the instance to be rebooted.

The following code reboots the instance `sample-instance`.

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb reboot-db-instance \
       --db-instance-identifier sample-instance
```
For Windows:  

```
aws docdb reboot-db-instance ^
       --db-instance-identifier sample-instance
```
Output from this operation looks something like the following.  

```
{
    "DBInstance": {
        "DBInstanceIdentifier": "sample-instance",
        "DBInstanceClass": "db.r5.large",
        "Engine": "docdb",
        "DBInstanceStatus": "rebooting",
        "Endpoint": {
            "Address": "sample-instance.node.us-east-1.docdb.amazonaws.com",
            "Port": 27017,   
            "HostedZoneId": "ABCDEFGHIJKLM"
        },
        "InstanceCreateTime": "2020-03-27T08:05:56.314Z",
        "PreferredBackupWindow": "02:00-02:30",
        "BackupRetentionPeriod": 1,
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-abcd0123",
                "Status": "active"
            }
        ],
        "AvailabilityZone": "us-east-1c",
        "DBSubnetGroup": {
            "DBSubnetGroupName": "default",
            "DBSubnetGroupDescription": "default",
            "VpcId": "vpc-abcd0123",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-abcd0123",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1a"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-wxyz0123",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1b"
                    },
                    "SubnetStatus": "Active"
                }
            ]
        },
        "PreferredMaintenanceWindow": "sun:06:53-sun:07:23",
        "PendingModifiedValues": {},
        "EngineVersion": "3.6.0",
        "AutoMinorVersionUpgrade": true,
        "PubliclyAccessible": false,
        "DBClusterIdentifier": "sample-cluster",
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:us-east-1:<accountID>:key/sample-key",
        "DbiResourceId": "db-ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "CACertificateIdentifier": "rds-ca-2019",
        "PromotionTier": 1,
        "DBInstanceArn": "arn:aws:rds:us-east-1:<accountID>:db:sample-instance",
        "EnabledCloudwatchLogsExports": [
            "profiler"
        ]
    }
}
```

It takes a few minutes for your instance to reboot. You can use the instance only when its status is *available*. You can monitor the instance's status using the console or AWS CLI. For more information, see [Monitoring an Amazon DocumentDB instance's status](monitoring_docdb-instance_status.md). 

------

# Deleting an Amazon DocumentDB instance
<a name="db-instance-delete"></a>

You can delete your Amazon DocumentDB instance using either the AWS Management Console or the AWS CLI. To delete an instance, the instance must be in the *available* state. You cannot delete an instance that is stopped. If the Amazon DocumentDB cluster that contains your instance is stopped, first start the cluster, wait for the instance to become *available*, and then delete the instance. For more information, see [Stopping and starting an Amazon DocumentDB cluster](db-cluster-stop-start.md). 

**Note**  
Amazon DocumentDB stores all of your data in the cluster volume. The data persists in that cluster volume, even if you remove all the instances from your cluster. If you need to access the data again, you can add an instance to the cluster at any time and pick up where you left off.

------
#### [ Using the AWS Management Console ]

The following procedure deletes a specified Amazon DocumentDB instance using the console.

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters **.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the Clusters navigation box, you’ll see the column **Cluster Identifier**. Your instances are listed under clusters, similar to the screenshot below.  
![\[Clusters table showing list of clusters under Cluster identifier column, with instances nested inside clusters.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/choose-clusters.png)

1. Check the box to the left of the instance you wish to delete.

1. Select **Actions**, and then choose **Delete**.

   1. If you are deleting the last instance in your cluster:
      + **Create final cluster snapshot?** — Choose **Yes** if you want to create a final snapshot before the cluster is deleted. Otherwise, choose **No**.
      + **Final snapshot name** — If you choose to create a final snapshot, enter the cluster snapshot identifier of the new cluster snapshot created.
      + **Delete <instance-name> instance?** — Enter the phrase **delete entire cluster** into the field to confirm the deletion.

   1. If you are not deleting the last instance in your cluster:
      + **Delete <instance-name> instance?** — Enter the phrase **delete me** into the field to confirm the deletion. 

1. Select **Delete** to delete the instance. 

It takes several minutes for an instance to be deleted. To monitor the status of an instance, see [Monitoring an Amazon DocumentDB instance's status](monitoring_docdb-instance_status.md). 

------
#### [ Using the AWS CLI ]

The following procedure deletes an Amazon DocumentDB instance using the AWS CLI.

1. **First, determine how many instances are in your Amazon DocumentDB cluster:** 

   To determine how many instances are in your cluster, run the `describe-db-clusters` command, as follows.

   ```
   aws docdb describe-db-clusters \
       --db-cluster-identifier sample-cluster \
       --query 'DBClusters[*].[DBClusterIdentifier,DBClusterMembers[*].DBInstanceIdentifier]'
   ```

   Output from this operation looks something like the following.

   ```
   [
       [
           "sample-cluster",
           [
               "sample-instance-1",
               "sample-instance-2"
           ]
       ]
   ]
   ```

1. **If there are more than one instances in your Amazon DocumentDB cluster:**

   To delete a specified Amazon DocumentDB instance, use the `delete-db-instance` command with the `--db-instance-identifier` parameter, as shown below. It takes several minutes for an instance to be deleted. To monitor the status of an instance, see [Monitoring an Amazon DocumentDB instance's status](monitoring_docdb-instance_status.md). 

   ```
   aws docdb delete-db-instance \
          --db-instance-identifier sample-instance-2
   ```

   Output from this operation looks something like the following.

   ```
   {
       "DBInstance": {
           "DBInstanceIdentifier": "sample-instance-2",
           "DBInstanceClass": "db.r5.large",
           "Engine": "docdb",
           "DBInstanceStatus": "deleting",
           "Endpoint": {
               "Address": "sample-instance-2.node.us-east-1.docdb.amazonaws.com",
               "Port": 27017,
               "HostedZoneId": "ABCDEFGHIJKLM"
           },
           "InstanceCreateTime": "2020-03-27T08:05:56.314Z",
           "PreferredBackupWindow": "02:00-02:30",
           "BackupRetentionPeriod": 1,
           "VpcSecurityGroups": [
               {
                   "VpcSecurityGroupId": "sg-abcd0123",
                   "Status": "active"
               }
           ],
           "AvailabilityZone": "us-east-1c",
           "DBSubnetGroup": {
               "DBSubnetGroupName": "default",
               "DBSubnetGroupDescription": "default",
               "VpcId": "vpc-6242c31a",
               "SubnetGroupStatus": "Complete",
               "Subnets": [
                   {
                       "SubnetIdentifier": "subnet-abcd0123",
                       "SubnetAvailabilityZone": {
                           "Name": "us-east-1a"
                       },
                       "SubnetStatus": "Active"
                   },
                   {
                       "SubnetIdentifier": "subnet-wxyz0123",
                       "SubnetAvailabilityZone": {
                           "Name": "us-east-1b"
                       },
                       "SubnetStatus": "Active"
                   }
               ]
           },
           "PreferredMaintenanceWindow": "sun:06:53-sun:07:23",
           "PendingModifiedValues": {},
           "EngineVersion": "3.6.0",
           "AutoMinorVersionUpgrade": true,
           "PubliclyAccessible": false,
           "DBClusterIdentifier": "sample-cluster",
           "StorageEncrypted": true,
           "KmsKeyId": "arn:aws:kms:us-east-1:<accountID>:key/sample-key",
           "DbiResourceId": "db-ABCDEFGHIJKLMNOPQRSTUVWXYZ",
           "CACertificateIdentifier": "rds-ca-2019",
           "PromotionTier": 1,
           "DBInstanceArn": "arn:aws:rds:us-east-1:<accountID>:db:sample-instance-2",
           "EnabledCloudwatchLogsExports": [
               "profiler"
           ]
       }
   }
   ```

1. **If the instance your want to delete is the last instance in your Amazon DocumentDB cluster: **

   If you delete the last instance in an Amazon DocumentDB cluster, you also delete that cluster and the automatic snapshots and continuous backups associated with that cluster.

   To delete the last instance in your cluster, you can delete the cluster and optionally create a final snapshot. For more information, see [Deleting an Amazon DocumentDB cluster](db-cluster-delete.md). 

------

## Deletion protection
<a name="db-instance-delete-deletion-protection"></a>

Deleting the last instance of an Amazon DocumentDB cluster will also delete the cluster, as well as the automatic snapshots and continuous backups associated with that cluster. Amazon DocumentDB enforces deletion protection for a cluster whether you perform the delete operation using the AWS Management Console or the AWS CLI. If deletion protection is enabled, you can't delete a cluster.

To delete a cluster that has deletion protection enabled, you must first modify the cluster and disable deletion protection. For more information, see [Deleting an Amazon DocumentDB cluster](db-cluster-delete.md). 

# Managing instance classes
<a name="db-instance-classes"></a>

The instance class determines the computation and memory capacity of an Amazon DocumentDB (with MongoDB compatibility) instance. The instance class you need depends on your processing power and memory requirements. 

Amazon DocumentDB supports the R4, R5, R6G, R8G, T3, and T4G families of instance classes. These classes are current-generation instance classes that are optimized for memory-intensive applications. For the specifications on these classes, see [Instance class specifications](#db-instance-class-specs). 

**Topics**
+ [

## Determining an instance class
](#db-instance-class-determining)
+ [

## Changing an instance's class
](#db-instance-class-changing)
+ [

## Supported instance classes by region
](#db-instance-classes-by-region)
+ [

## Instance class specifications
](#db-instance-class-specs)

## Determining an instance class
<a name="db-instance-class-determining"></a>

To determine the class of an instance, you can use the AWS Management Console or the `describe-db-instances` AWS CLI operation.

------
#### [ Using the AWS Management Console ]

To determine the instance class for your cluster's instances, complete the following steps in the console.

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters **to find the instance that you're interested in. 
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the Clusters navigation box, you’ll see the column **Cluster Identifier**. Your instances are listed under clusters, similar to the screenshot below.  
![\[Clusters table showing how an instance is nested under a cluster.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/choose-clusters.png)

1. In the list of instances, expand the cluster to find the instances you are interested in. Find the instance that you want. Then, look at the **Size** column of the instance's row to see its instance class.

   In the following image, the instance class for instance `robo3t` is `db.r5.4xlarge`.  
![\[List of instances in the Clusters table with the Size column showing the instance type.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/instance-class.png)

------
#### [ Using the AWS CLI ]

To determine the class of an instance using the AWS CLI, use the `describe-db-instances` operation with the following parameters.
+ **--db-instance-identifier** — Optional. Specifies the instance that you want to find the instance class for. If this parameter is omitted, `describe-db-instances` returns a description for up to 100 of your instances.
+ **--query** — Optional. Specifies the members of the instance to include in the results. If this parameter is omitted, all instance members are returned.

**Example**  
The following example finds the instance name and class for the instance `sample-instance-1`.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-instances \
    --query 'DBInstances[*].[DBInstanceIdentifier,DBInstanceClass]' \
    --db-instance-identifier sample-instance-1
```
For Windows:  

```
aws docdb describe-db-instances ^
    --query 'DBInstances[*].[DBInstanceIdentifier,DBInstanceClass]' ^
    --db-instance-identifier sample-instance-1
```
Output from this operation looks something like the following.  

```
[
    [
        "sample-instance-1",
        "db.r5.large"
    ]
```

**Example**  
The following example finds the instance name and class for up to 100 Amazon DocumentDB instances.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-instances \
    --query 'DBInstances[*].[DBInstanceIdentifier,DBInstanceClass]' \
    --filter Name=engine,Values=docdb
```
For Windows:  

```
aws docdb describe-db-instances ^
    --query 'DBInstances[*].[DBInstanceIdentifier,DBInstanceClass]' ^
    --filter Name=engine,Values=docdb
```
Output from this operation looks something like the following.  

```
[
    [
        "sample-instance-1",
        "db.r5.large"
    ],
    [
        "sample-instance-2",
        "db.r5.large"
    ],
    [
        "sample-instance-3",
        "db.r5.4xlarge"
    ],
    [
        "sample-instance-4",
        "db.r5.4xlarge"
    ]
]
```

For more information, see [Describing Amazon DocumentDB instances](db-instance-view-details.md). 

------

## Changing an instance's class
<a name="db-instance-class-changing"></a>

You can change the instance class of your instance using the AWS Management Console or the AWS CLI. For more information, see [Modifying an Amazon DocumentDB instance](db-instance-modify.md). 

## Supported instance classes by region
<a name="db-instance-classes-by-region"></a>

Amazon DocumentDB supports the following instance classes:
+ `R8G`—Latest generation of memory-optimized instances powered by Arm-based AWS Graviton4 processors that provide up to 30% better performance over R6G instances.
+ `R6G`—Memory-optimized instances powered by Arm-based AWS Graviton2 processors that provide up to 30% better performance over R5 instances at 5% less cost.
+ `R6GD`—Memory-optimized R6G instances with local non-volatile memory express (NVMe)-based Solid-State Drive (SSD) storage for ephemeral data.
+ `R5`—Memory-optimized instances that provide up to 100% better performance over R4 instances for the same instance cost.
+ `R4`—Previous generation of memory-optimized instances.
+ `T4G`—Latest-generation low cost burstable general-purpose instance type powered by Arm-based AWS Graviton2 processors that provides a baseline level of CPU performance, delivering up to 35% better price performance over T3 instances and ideal for running applications with moderate CPU usage that experience temporary spikes in usage.
+ `T3`—Low cost burstable general-purpose instance type that provides a baseline level of CPU performance with the ability to burst CPU usage at any time for as long as required.

For detailed specifications on the instance classes, see [Instance class specifications](#db-instance-class-specs). 

**Note**  
I/O-Optimized storage is only available on engine versions 5.0 and 8.0 (instance-based clusters).

A particular instance class may or may not be supported in a given Region. The following table specifies which instance classes are supported by Amazon DocumentDB in each Region.


**Supported instance classes by Region**  

|  | Instance Classes | Region | R8G | R6GD | R6G | R5 | R4 | T4G | T3 | Serverless | 
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | 
| US East (Ohio) | Supported | Supported | Supported | Supported | Supported | Supported | Supported | Supported | 
| US East (N. Virginia) | Supported | Supported | Supported | Supported | Supported | Supported | Supported | Supported | 
| US West (Oregon) | Supported | Supported | Supported | Supported | Supported | Supported | Supported | Supported | 
| Africa (Cape Town) |  |  | Supported | Supported |  | Supported | Supported | Supported | 
| South America (São Paulo) |  | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Asia Pacific (Hong Kong) |  |  | Supported | Supported |  | Supported | Supported | Supported | 
| Asia Pacific (Hyderabad) |  |  | Supported | Supported |  | Supported | Supported | Supported | 
| Asia Pacific (Malaysia) |  |  | Supported |  |  | Supported | Supported |  | 
| Asia Pacific (Mumbai) | Supported | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Asia Pacific (Osaka) |  | Supported | Supported | Supported |  | Supported | Supported |  | 
| Asia Pacific (Seoul) | Supported | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Asia Pacific (Sydney) | Supported | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Asia Pacific (Jakarta) | Supported | Supported | Supported | Supported |  | Supported | Supported |  | 
| Asia Pacific (Melbourne) |  |  | Supported | Supported |  | Supported | Supported |  | 
| Asia Pacific (Singapore) | Supported | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Asia Pacific (Thailand) |  |  | Supported |  |  | Supported | Supported |  | 
| Asia Pacific (Tokyo) | Supported | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Canada (Central) |  | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Europe (Frankfurt) | Supported | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Europe (Zurich) |  | Supported | Supported | Supported |  | Supported | Supported |  | 
| Europe (Ireland) | Supported | Supported | Supported | Supported | Supported | Supported | Supported | Supported | 
| Europe (London) |  | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Europe (Milan) |  |  | Supported | Supported |  | Supported | Supported | Supported | 
| Europe (Paris) |  | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Europe (Spain) | Supported | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| Europe (Stockholm) | Supported | Supported | Supported | Supported |  | Supported | Supported |  | 
| Mexico (Central) |  |  | Supported |  |  | Supported | Supported |  | 
| Middle East (UAE) |  |  | Supported | Supported |  | Supported | Supported | Supported | 
| China (Beijing) |  | Supported | Supported | Supported |  | Supported | Supported | Supported | 
| China (Ningxia) |  |  | Supported | Supported |  | Supported | Supported | Supported | 
| Israel (Tel Aviv) |  |  | Supported | Supported |  | Supported | Supported | Supported | 
| AWS GovCloud (US-West) | Supported | Supported | Supported | Supported |  |  | Supported | Supported | 
| AWS GovCloud (US-East) |  | Supported | Supported | Supported |  | Supported | Supported | Supported | 

## Instance class specifications
<a name="db-instance-class-specs"></a>

The following table provides details of the Amazon DocumentDB instance classes, including which instance types are supported in each class. You can find explanations for each table column below the table.


| Instance class | vCPU1 | Memory (GiB)2 | NVMe SSD tiered cache (GiB)3 | Max. temp. storage (GiB)4 | Baseline / burst bandwidth (Gbps)5 | Supporting Engines6 | 
| --- | --- | --- | --- | --- | --- | --- | 
| R8G – Current Generation Memory-Optimized Instance Class based on Graviton4 R8G is the newest instance family (Graviton4), available on engine versions 5.0 and 8.0 only. Sizes db.r8g.24xlarge and db.r8g.48xlarge are not yet available. | 
| db.r8g.large | 2 | 16 | - | 30 | 0.937 / 12.5 | 5.0.0 and 8.0.0 | 
| db.r8g.xlarge | 4 | 32 | - | 60 | 1.875 / 12.5 | 5.0.0 and 8.0.0 | 
| db.r8g.2xlarge | 8 | 64 | - | 121 | 3.75 / 15.0 | 5.0.0 and 8.0.0 | 
| db.r8g.4xlarge | 16 | 128 | - | 243 | 7.5 / 15.0 | 5.0.0 and 8.0.0 | 
| db.r8g.8xlarge | 32 | 256 | - | 488 | 15 | 5.0.0 and 8.0.0 | 
| db.r8g.12xlarge | 48 | 384 | - | 732 | 22 | 5.0.0 and 8.0.0 | 
| db.r8g.16xlarge | 64 | 512 | - | 987 | 30 | 5.0.0 and 8.0.0 | 
| R6G – Current Generation Memory-Optimized Instance Class based on Graviton2 | 
| db.r6g.large | 2 | 16 | - | 32 | 0.75 / 10 | 4.0.0, 5.0.0, and 8.0.0 | 
| db.r6g.xlarge | 4 | 32 | - | 63 | 1.25 / 10 | 4.0.0, 5.0.0, and 8.0.0 | 
| db.r6g.2xlarge | 8 | 64 | - | 126 | 2.5 / 10 | 4.0.0, 5.0.0, and 8.0.0 | 
| db.r6g.4xlarge | 16 | 128 | - | 252 | 5.0 / 10 | 4.0.0, 5.0.0, and 8.0.0 | 
| db.r6g.8xlarge | 32 | 256 | - | 504 | 12 | 4.0.0, 5.0.0, and 8.0.0 | 
| db.r6g.12xlarge | 48 | 384 | - | 756 | 20 | 4.0.0, 5.0.0, and 8.0.0 | 
| db.r6g.16xlarge | 64 | 512 | - | 1008 | 25 | 4.0.0, 5.0.0, and 8.0.0 | 
| R6GD – Current Generation NVMe-backed Instance Class based on Graviton2 | 
| db.r6gd.xlarge | 4 | 32 | 173 | 64 | 1.25 / 10 | 5.0.0 and 8.0.0 | 
| db.r6gd.2xlarge | 8 | 64 | 346 | 128 | 2.5 / 10 | 5.0.0 and 8.0.0 | 
| db.r6gd.4xlarge | 16 | 128 | 694 | 256 | 5.0 / 10 | 5.0.0 and 8.0.0 | 
| db.r6gd.8xlarge | 32 | 256 | 1388 | 512 | 12 | 5.0.0 and 8.0.0 | 
| db.r6gd.12xlarge | 48 | 384 | 2082 | 768 | 20 | 5.0.0 and 8.0.0 | 
| db.r6gd.16xlarge | 64 | 512 | 2776 | 1024 | 25 | 5.0.0 and 8.0.0 | 
| R5 – Previous Generation Memory-Optimized Instance Class | 
| db.r5.large | 2 | 16 | - | 31 | 0.75 / 10 | 3.6.0, 4.0.0, 5.0.0, and 8.0.0 | 
| db.r5.xlarge | 4 | 32 | - | 62 | 1.25 / 10 | 3.6.0, 4.0.0, 5.0.0, and 8.0.0 | 
| db.r5.2xlarge | 8 | 64 | - | 124 | 2.5 / 10 | 3.6.0, 4.0.0, 5.0.0, and 8.0.0 | 
| db.r5.4xlarge | 16 | 128 | - | 249 | 5.0 / 10 | 3.6.0, 4.0.0, 5.0.0, and 8.0.0 | 
| db.r5.8xlarge | 32 | 256 | - | 504 | 10 | 3.6.0, 4.0.0, 5.0.0, and 8.0.0 | 
| db.r5.12xlarge | 48 | 384 | - | 748 | 12 | 3.6.0, 4.0.0, 5.0.0, and 8.0.0 | 
| db.r5.16xlarge | 64 | 512 | - | 1008 | 20 | 3.6.0, 4.0.0, 5.0.0, and 8.0.0 | 
| db.r5.24xlarge | 96 | 768 | - | 1500 | 25 | 3.6.0, 4.0.0, 5.0.0, and 8.0.0 | 
| R4 – Previous Generation Memory-Optimized Instance Class R4 instances are only supported on engine version 3.6. Note that Amazon DocumentDB 3.6 reaches end of standard support on March 30, 2026. Extended Support (paid) is available until March 2029. | 
| db.r4.large | 2 | 15.25 | - | 30 | 0.75 / 10 | 3.6.0 only | 
| db.r4.xlarge | 4 | 30.5 | - | 60 | 1.25 / 10 | 3.6.0 only | 
| db.r4.2xlarge | 8 | 61 | - | 120 | 2.5 / 10 | 3.6.0 only | 
| db.r4.4xlarge | 16 | 122 | - | 240 | 5.0 /10 | 3.6.0 only | 
| db.r4.8xlarge | 32 | 244 | - | 480 | 10 | 3.6.0 only | 
| db.r4.16xlarge | 64 | 488 | - | 960 | 25 | 3.6.0 only | 
| T4G – Latest Generation Burstable Performance Instance Classes based on Graviton2 T-series instances run in Unlimited CPU burst mode. Burst usage beyond the baseline is billed extra. Not supported for Global Clusters. | 
| db.t4g.medium | 2 | 4 | - | 8.13 | 0.256 / 5 | 4.0.0, 5.0.0, and 8.0.0 | 
| T3 – Previous Generation Burstable Performance Instance Classes | 
| db.t3.medium | 2 | 4 | - | 7.5 | 0.256 / 5 | 3.6.0, 4.0.0, 5.0.0, and 8.0.0 | 
|  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/db-instance-classes.html)  | 

# NVMe-backed instances
<a name="db-instance-nvme"></a>

NVMe-backed instances offer up to 7x faster query performance for applications with large datasets that exceed the memory of a regular instance. These instances leverage the local non-volatile memory express (NVMe)-based Solid-State Drive (SSD) storage available on r6gd instances to store ephemeral data, reducing network-based storage access, and improving read latency and throughput.

The local SSD space is divided into two sections:
+ **Tiered cache** — Approximately 73% of the local SSD is allocated as a database cache, allowing the system to store up to five times more database pages than the main memory alone. The local SSD acts as a second-tier cache, while the existing in-memory buffer cache remains the first-tier cache. The query only accesses external storage if both the buffer cache and the SSD cache experience a miss.
+ **Temporary storage** — The remaining 27% is reserved for non-persistent temporary file storage, used for complex queries involving sorts or resource-intensive operations like index builds. On regular instances, the temporary space resides on an Amazon Elastic Block Store (EBS) volume. The locally hosted temporary storage on the SSD reduces query latency involving sorts by up to two times and accelerates resource-intensive operations like index builds.

The details regarding the type of NVMe-backed instances supported and its specification can be found in [Instance class specifications](db-instance-classes.md#db-instance-class-specs).

**Topics**
+ [

## Recommended use cases for NVMe-backed instances
](#nvme-use-cases)
+ [

## Using NVMe-backed instances with Amazon DocumentDB
](#using-nvme)
+ [

## Monitoring NVMe-backed instances
](#monitoring-nvme)

## Recommended use cases for NVMe-backed instances
<a name="nvme-use-cases"></a>

We recommend you use NVMe-backed instances in the following scenarios:
+ **Read-heavy workloads** — If your workload is read-intensive, and your dataset is larger than the buffer cache, indicated by low `BufferCacheHitRatio` and high `ReadIOPS` metrics, NVMe-backed instances can provide performance benefits.
+ **Update-heavy workloads** — If your workload is update-intensive, and garbage collection is unable to keep up due to read latency on network storage, NVMe-backed instances could help mitigate the issue.

NVMe-backed instances can benefit various use cases, including:
+ **Internet-scale applications** — Applications such as payment processing, billing, and e-commerce with strict performance Service Level Agreements (SLAs) can leverage the performance advantages of NVMe-backed instances.
+ **Real-time reporting dashboards** — Dashboards that run hundreds of queries for metrics/data collection can benefit from the low latency and high throughput of NVMe-backed instances.
+ **Generative AI applications** — Applications using vector search to find exact or nearest neighbors across millions of vector embeddings can leverage the high performance of NVMe-backed instances.

## Using NVMe-backed instances with Amazon DocumentDB
<a name="using-nvme"></a>

To use NVMe-backed instances of Amazon DocumentDB:
+ Create an Amazon DocumentDB cluster and add one of the NVMe-backed instance classes. For more information, see [Creating an Amazon DocumentDB cluster](db-cluster-create.md).
+ Alternatively, modify an existing Amazon DocumentDB cluster to use one of the NVMe-backed instance classes. For more information, see [Modifying an Amazon DocumentDB cluster](db-cluster-modify.md).

To check the availability of NVMe-backed instances across different AWS Regions, see [Supported instance classes by region](db-instance-classes.md#db-instance-classes-by-region).

If you want to switch back from an NVMe-backed instance to a regular instance, modify the database instance class of your Amazon DocumentDB instance to a similar instance class without the NVMe storage. For example, if your current instance class is 'db.r6gd.4xlarge', choose 'db.r6g.4xlarge' to switch back. For more information, see [Modifying an Amazon DocumentDB cluster](db-cluster-modify.md).

## Monitoring NVMe-backed instances
<a name="monitoring-nvme"></a>

In addition to the regular instance metrics available in Amazon CloudWatch, NVMe-backed instances emit additional metrics specific to NVMe-based SSD storage, IOPS, and throughput. 

```
NVMeStorageCacheHitRatio
FreeNVMeStorage
ReadIOPSNVMeStorage
ReadLatencyNVMeStorage
ReadThroughputNVMeStorage
WriteIOPSNVMeStorage
WriteLatencyNVMeStorage
WriteThroughputNVMeStorage
```

For more information about these metrics, see [NVMe-backed instance metrics](cloud_watch.md#nvme-metrics)

# Managing Amazon DocumentDB subnet groups
<a name="document-db-subnet-groups"></a>

A virtual private cloud (VPC) is a virtual network dedicated to your AWS account. It is logically isolated from other virtual networks in the AWS Cloud. You can launch your AWS resources, such as Amazon DocumentDB clusters, into your Amazon VPC. You can specify an IP address range for the VPC, add subnets, associate security groups, and configure route tables. 

A subnet is a range of IP addresses in your Amazon VPC. You can launch AWS resources into a specified subnet. Use a *public* subnet for resources that must be connected to the internet. Use a *private* subnet for resources that won't be connected to the internet. For more information about public and private subnets, see [VPC and Subnet Basics](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html#vpc-subnet-basics) in the *Amazon Virtual Private Cloud User Guide*. 

A DB subnet group is a collection of subnets that you create in a VPC that you then designate for your clusters. A subnet group allows you to specify a particular VPC when creating clusters. If you use the `default` subnet group, it spans all subnets in the VPC.

Each DB subnet group should have subnets in at least two Availability Zones in a given Region. When creating a DB cluster in a VPC, you must select a DB subnet group. Amazon DocumentDB uses that DB subnet group and your preferred Availability Zone to select a subnet and an IP address within that subnet to associate with your cluster. If the primary instance fails, Amazon DocumentDB can promote a corresponding replica instance to be the new primary. It can then create a new replica instance using an IP address of the subnet in which the previous primary was located.

When Amazon DocumentDB creates an instance in a VPC, it assigns a network interface to your cluster by using an IP address selected from your DB subnet group. We strongly recommend that you use the DNS name because the underlying IP address can change during failover. For more information, see [Amazon DocumentDB endpoints](how-it-works.md#how-it-works.endpoints).

For information about creating your own VPC and subnets, see [Working with VPCs and Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html) in the *Amazon Virtual Private Cloud User Guide*.

**Topics**
+ [

# Creating an Amazon DocumentDB subnet group
](document-db-subnet-group-create.md)
+ [

# Describing an Amazon DocumentDB subnet group
](document-db-subnet-group-describe.md)
+ [

# Modifying an Amazon DocumentDB subnet group
](document-db-subnet-group-modify.md)
+ [

# Deleting an Amazon DocumentDB subnet group
](document-db-subnet-group-delete.md)

# Creating an Amazon DocumentDB subnet group
<a name="document-db-subnet-group-create"></a>

When creating an Amazon DocumentDB cluster, you must choose a Amazon VPC and corresponding subnet group within that Amazon VPC to launch your cluster. Subnets determine the availability zone and IP range within the availability zone that you want to use to launch an instance. 

A subnet group is a named set of subnets (or AZs) that allows you to specify the availability zones that you want to use to for launching Amazon DocumentDB instances. For example, in a cluster with three instances, it is recommended that each of those instances are provisioned in separate AZs—doing so optimizes for high availability. Thus, if a single AZ fails, it will only affect a single instance. 

Currently, Amazon DocumentDB instances can be provisioned in up to three AZs. Even if a subnet group has more than three subnets, you will only be able to use three of those subnets to create an Amazon DocumentDB cluster. Therefore, we recommend that when you create a subnet group that you only choose the three subnets of which you want to deploy your instances. 

For example: A cluster is created and Amazon DocumentDB choose AZs \$11A, 1B, and 1C\$1. If you attempt to create an instance in AZ \$11D\$1 the API call will fail. However, if you choose to create an instance, without specifying the particular AZ, then Amazon DocumentDB will choose an AZ on your behalf. Amazon DocumentDB uses an algorithm to load balance the instances across AZs to help you achieve high availability. If three instances are provisioned, by default, they will be provisioned across three AZs and will not be provisioned all in a single AZ.

Best Practices
+ Unless you have a specific reason, always create a subnet group with three subnets. This ensures that clusters with three or more instances will be able to achieve higher availability as instances will be provisioned across three AZs.
+ Always spread instances across multiple AZs to achieve high availability. Never place all instances for a cluster in a single AZ.
+ Because failover events can happen at any time, you should not assume that a primary instance or replica instances will always be in a particular AZ.

## How to create a subnet group
<a name="document-db-subnet-group-how-create"></a>

You can use the AWS Management Console or AWS CLI to create an Amazon DocumentDB subnet group:

------
#### [ Using the AWS Management Console ]

Use the following steps to create an Amazon DocumentDB subnet group.

**To create an Amazon DocumentDB subnet group**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Subnet groups**, then choose **Create**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. On the **Create subnet group** page:

   1. In the **Subnet group details** section:

      1. **Name**—Enter a meaningful name for the subnet group.

      1. **Description**—Enter a description for the subnet group.

   1. In the **Add subnets** section:

      1. **VPC**—In the list, choose a VPC for this subnet group.

      1. Do one of the following:
         + To include all subnets in the chosen VPC, choose **Add all the subnets related to this VPC**.
         + To specify subnets for this subnet group, do the following for each Availability Zone for which you want to include subnets. You must include at least two Availability Zones.

           1. **Availability zone**—In the list, choose an Availability Zone.

           1. **Subnet**—In the list, choose a subnet from the chosen Availability Zone for this subnet group.

           1. Choose **Add subnet**.

1. Choose **Create**. When the subnet group is created, it is listed with your other subnet groups.  
![\[Screenshot: Showing the details of a subnet group.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-subnet-groups-list.png)

------
#### [ Using the AWS CLI ]

Before you can create a subnet group using the AWS CLI, you must first determine which subnets are available. Run the following AWS CLI operation to list the Availability Zones and their subnets.

**Parameters:**
+ **--db-subnet-group**—Optional. Specifying a particular subnet group lists the Availability Zones and subnets for that group. Omitting this parameter lists Availability Zones and subnets for all your subnet groups. Specifying the `default` subnet group lists all the VPC's subnets.

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-subnet-groups \
    --db-subnet-group-name default \
    --query 'DBSubnetGroups[*].[DBSubnetGroupName,Subnets[*].[SubnetAvailabilityZone.Name,SubnetIdentifier]]'
```
For Windows:  

```
aws docdb describe-db-subnet-groups ^
    --db-subnet-group-name default ^
    --query 'DBSubnetGroups[*].[DBSubnetGroupName,Subnets[*].[SubnetAvailabilityZone.Name,SubnetIdentifier]]'
```
Output from this operation looks something like the following (JSON format).  

```
[
    [
        "default",
        [
            [
                "us-east-1a",
                "subnet-4e26d263"
            ],
            [
                "us-east-1c",
                "subnet-afc329f4"
            ],
            [
                "us-east-1e",
                "subnet-b3806e8f"
            ],
            [
                "us-east-1d",
                "subnet-53ab3636"
            ],
            [
                "us-east-1b",
                "subnet-991cb8d0"
            ],
            [
                "us-east-1f",
                "subnet-29ab1025"
            ]
        ]
    ]
]
```
Using the output from the previous operation, you can create a new subnet group. The new subnet group must include subnets from at least two Availability Zones.  

**Parameters:**
+ **--db-subnet-group-name**—Required. The name for this subnet group.
+ **--db-subnet-group-description**—Required. The description of this subnet group.
+ **--subnet-ids**—Required. A list of subnets to include in this subnet group. Example: `subnet-53ab3636`.
+ --Tags****—Optional. A list of tags (key-value pairs) to attach to this subnet group.
The following code creates the subnet group `sample-subnet-group` with three subnets, `subnet-4e26d263`, `subnet-afc329f4`, and `subnet-b3806e8f`.  
For Linux, macOS, or Unix:  

```
aws docdb create-db-subnet-group \
    --db-subnet-group-name sample-subnet-group \
    --db-subnet-group-description "A sample subnet group" \
    --subnet-ids subnet-4e26d263 subnet-afc329f4 subnet-b3806e8f \
    --tags Key=tag1,Value=One Key=tag2,Value=2
```
For Windows:  

```
aws docdb create-db-subnet-group ^
    --db-subnet-group-name sample-subnet-group ^
    --db-subnet-group-description "A sample subnet group" ^
    --subnet-ids subnet-4e26d263 subnet-afc329f4 subnet-b3806e8f ^
    --tags Key=tag1,Value=One Key=tag2,Value=2
```
Output from this operation looks something like the following (JSON format).  

```
{
    "DBSubnetGroup": {
        "DBSubnetGroupDescription": "A sample subnet group",
        "DBSubnetGroupName": "sample-subnet-group",
        "Subnets": [
            {
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1a"
                },
                "SubnetIdentifier": "subnet-4e26d263",
                "SubnetStatus": "Active"
            },
            {
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1c"
                },
                "SubnetIdentifier": "subnet-afc329f4",
                "SubnetStatus": "Active"
            },
            {
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1e"
                },
                "SubnetIdentifier": "subnet-b3806e8f",
                "SubnetStatus": "Active"
            }
        ],
        "VpcId": "vpc-91280df6",
        "DBSubnetGroupArn": "arn:aws:rds:us-east-1:123SAMPLE012:subgrp:sample-subnet-group",
        "SubnetGroupStatus": "Complete"
    }
}
```

------

# Describing an Amazon DocumentDB subnet group
<a name="document-db-subnet-group-describe"></a>

You can use the AWS Management Console or the AWS CLI to get the details of an Amazon DocumentDB subnet group.

------
#### [ Using the AWS Management Console ]

The following procedure shows you how to get the details of an Amazon DocumentDB subnet group.

**To find the details of a subnet group**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Subnet groups**. 
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. To see the details of a subnet group, choose the name of that subnet group.  
![\[Screenshot: Showing the details of a subnet group.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-subnet-group-details.png)

------
#### [ Using the AWS CLI ]

To find the details of an Amazon DocumentDB subnet group, use the `describe-db-subnet-groups` operation with the following parameter.

**Parameter**
+ `--db-subnet=group-name`—Optional. If included, details for the named subnet group are listed. If omitted, details for up to 100 subnet groups are listed.

**Example**  
The following code lists details for the `sample-subnet-group` subnet group that we created in the [Creating an Amazon DocumentDB subnet group](document-db-subnet-group-create.md) section.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-subnet-groups \
    --db-subnet-group-name sample-subnet-group
```
For Windows:  

```
aws docdb describe-db-subnet-groups ^
    --db-subnet-group-name sample-subnet-group
```
Output from this operation looks something like the following (JSON format).  

```
{
    "DBSubnetGroup": {
        "DBSubnetGroupArn": "arn:aws:rds:us-east-1:123SAMPLE012:subgrp:sample-subnet-group",
        "VpcId": "vpc-91280df6",
        "SubnetGroupStatus": "Complete",
        "DBSubnetGroupName": "sample-subnet-group",
        "Subnets": [
            {
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1a"
                },
                "SubnetStatus": "Active",
                "SubnetIdentifier": "subnet-4e26d263"
            },
            {
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1c"
                },
                "SubnetStatus": "Active",
                "SubnetIdentifier": "subnet-afc329f4"
            },
            {
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1e"
                },
                "SubnetStatus": "Active",
                "SubnetIdentifier": "subnet-b3806e8f"
            }
        ],
        "DBSubnetGroupDescription": "A sample subnet group"
    }
}
```

------

# Modifying an Amazon DocumentDB subnet group
<a name="document-db-subnet-group-modify"></a>

You can use the AWS Management Console or AWS CLI to modify a subnet group's description or to add or remove subnets from an Amazon DocumentDB subnet group. However, you cannot modify the `default` subnet group.

------
#### [ Using the AWS Management Console ]

You can use the AWS Management Console to change a subnet group's description or to add and remove subnets. Remember that when you're finished, you must have at least two Availability Zones associated with your subnet group.

**To modify your subnet group**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Subnet groups**. Then choose the button to the left of the subnet group's name. Remember that you can't modify the `default` subnet group.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. Choose **Actions**, and then choose **Modify**.

1. **Description**—To change the description of your subnet group, enter a new description.

1. To change the subnets associated with your subnet group, in the **Add subnets** section, do any one or more of the following:
   + To remove all subnets from this subnet group, choose **Remove all**.
   + To remove specific subnets from this subnet group, choose **Remove** for each subnet you want to remove.
   + To add all the subnets associated with this VPC, choose **Add all the subnets related to this VPC**.
   + To add specific subnets to this subnet group, do the following for each Availability Zone for which you want to add a subnet.

     1. **Availability zone**—In the list, choose a new Availability Zone.

     1. **Subnet**—In the list, choose a subnet from the chosen Availability Zone for this subnet group.

     1. Choose **Add subnet**.

1. In the confirmation dialog box:
   + To make these changes to the subnet group, choose **Modify**.
   + To keep the subnet group unchanged, choose **Cancel**.

------
#### [ Using the AWS CLI ]

You can use the AWS CLI to change a subnet group's description or to add and remove subnets. Remember that when you're finished, you must have at least two Availability Zones associated with your subnet group. You can't modify the `default` subnet group.

**Parameters:**
+ `--db-subnet-group-name`—Required. The name of the Amazon DocumentDB subnet group you are modifying.
+ `--subnet-ids`—Required. A list of all the subnets that you want in the subnet group after this change is done.
**Important**  
Any subnets currently in the subnet group that are not included in this list are removed from the subnet group. If you want to keep any of the subnets currently in the subnet group, you must include them in this list.
+ `--db-subnet-group-description`—Optional. The description of the subnet group.

**Example**  
The following code modifies the description and replaces the existing subnets with the subnets `subnet-991cb8d0`, `subnet-53ab3636`, and `subnet-29ab1025`.  
For Linux, macOS, or Unix:  

```
aws docdb modify-db-subnet-group \
    --db-subnet-group-name sample-subnet-group \
    --subnet-ids subnet-991cb8d0 subnet-53ab3636 subnet-29ab1025 \
    --db-subnet-group-description "Modified subnet group"
```
For Windows:  

```
aws docdb modify-db-subnet-group ^
    --db-subnet-group-name sample-subnet-group ^
    --subnet-ids subnet-991cb8d0 subnet-53ab3636 subnet-29ab1025 ^
    --db-subnet-group-description "Modified subnet group"
```
Output from this operation looks something like the following (JSON format). Notice that this is the same subnet group that was created in the [Creating an Amazon DocumentDB subnet group](document-db-subnet-group-create.md) section. However, the subnets in the subnet group are replaced with those listed in the `modify-db-subnet-group` operation.  

```
{
    "DBSubnetGroup": {
        "DBSubnetGroupArn": "arn:aws:rds:us-east-1:123SAMPLE012:subgrp:sample-subnet-group",
        "DBSubnetGroupDescription": "Modified subnet group",
        "SubnetGroupStatus": "Complete",
        "Subnets": [
            {
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1d"
                },
                "SubnetStatus": "Active",
                "SubnetIdentifier": "subnet-53ab3636"
            },
            {
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1b"
                },
                "SubnetStatus": "Active",
                "SubnetIdentifier": "subnet-991cb8d0"
            },
            {
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1f"
                },
                "SubnetStatus": "Active",
                "SubnetIdentifier": "subnet-29ab1025"
            }
        ],
        "VpcId": "vpc-91280df6",
        "DBSubnetGroupName": "sample-subnet-group"
    }
}
```

------

# Deleting an Amazon DocumentDB subnet group
<a name="document-db-subnet-group-delete"></a>

You can use the AWS Management Console or AWS CLI to delete an Amazon DocumentDB subnet group. However, you cannot delete the `default` subnet group.

------
#### [ Using the AWS Management Console ]

You can use the AWS Management Console to delete a subnet group. But you can't delete the `default` subnet group.

**To delete a subnet group**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Subnet groups**. Then choose the button to the left of the subnet group's name. Remember that you can't delete the `default` subnet group.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. Choose **Actions**, and then choose **Delete**.

1. In the confirmation dialog box:
   + To delete the subnet group, choose **Delete**.
   + To keep the subnet group, choose **Cancel**.

------
#### [ Using the AWS CLI ]

To delete an Amazon DocumentDB subnet group using the AWS CLI, use the `delete-db-subnet-group` operation with the following parameter.

**Parameter**
+ `--db-subnet-group-name`—Required. The name of the Amazon DocumentDB subnet group to delete. Remember that you can't delete the `default` subnet group.

**Example**  
The following code deletes `sample-subnet-group`.  
For Linux, macOS, or Unix:  

```
aws docdb delete-db-subnet-group \
    --db-subnet-group-name sample-subnet-group
```
For Windows:  

```
aws docdb delete-db-subnet-group ^
    --db-subnet-group-name sample-subnet-group
```
This operation produces no output.

------

# Amazon DocumentDB High availability and replication
<a name="replication"></a>

You can achieve high availability and read scaling in Amazon DocumentDB (with MongoDB compatibility) by using replica instances. A single Amazon DocumentDB cluster supports a single primary instance and up to 15 replica instances. These instances can be distributed across Availability Zones within the cluster's Region. The primary instance accepts read and write traffic, and replica instances accept only read requests.

The cluster volume is made up of multiple copies of the data for the cluster. However, the data in the cluster volume is represented as a single, logical volume to the primary instance and to Amazon DocumentDB replicas in the cluster. Replica instances are eventually consistent. They return query results with minimal replica lag—usually much less than 100 milliseconds after the primary instance has written an update. Replica lag varies depending on the rate of database change. That is, during periods in which a large number of write operations occur for the database, you might see an increase in the replica lag. 

## Read scaling
<a name="replication.read-scaling"></a>

Amazon DocumentDB replicas work well for read scaling because they are fully dedicated to read operations on your cluster volume. Write operations are managed by the primary instance. The cluster volume is shared among all instances in your cluster. Therefore, you don't have to replicate and maintain a copy of the data for each Amazon DocumentDB replica. 

## High availability
<a name="replication.high-availability"></a>

When you create an Amazon DocumentDB cluster, depending upon the number of Availability Zones in the subnet group (there must be at least two), Amazon DocumentDB provisions instances across the Availability Zones. When you create instances in the cluster, Amazon DocumentDB automatically distributes the instances across the Availability Zones in a subnet group to balance the cluster. This action also prevents all instances from being located in the same Availability Zone.

**Example**  
To illustrate the point, consider an example where you create a cluster that has a subnet group with three Availability Zones: *AZ1*, *AZ2*, and *AZ3*.

When the first instance in the cluster is created, it is the primary instance and is located in one of the Availability Zones. In this example, it's in *AZ1*. The second instance created is a replica instance and is located in one of the other two Availability Zones, say *AZ2*. The third instance created is a replica instance and is located in the remaining Availability Zone, *AZ3*. If you create more instances, they are distributed across the Availability Zones so that you achieve balance in the cluster.

If a failure occurs in the primary instance (AZ1), a failover is triggered, and one of the existing replicas is promoted to primary. When the old primary recovers, it becomes a replica in the same Availability Zone in which it was provisioned (AZ1). When you provision a three-instance cluster, Amazon DocumentDB continues to preserve that three-instance cluster. Amazon DocumentDB automatically handles detection, failover, and recovery of instance failures without any manual intervention.

When Amazon DocumentDB performs a failover and recovers an instance, the recovered instance remains in the Availability Zone in which it was originally provisioned. However, the role of the instance might change from primary to replica. Doing this prevents the scenario in which a series of failovers could result in all instances being in the same Availability Zone.

You can specify Amazon DocumentDB replicas as failover targets. That is, if the primary instance fails, the specified Amazon DocumentDB replica or replica from a tier is promoted to the primary instance. There is a brief interruption during which read and write requests made to the primary instance fail with an exception. If your Amazon DocumentDB cluster doesn't include any Amazon DocumentDB replicas, when the primary instance fails, it is re-created. Promoting an Amazon DocumentDB replica is much faster than re-creating the primary instance. 

For high availability scenarios, we recommend that you create one or more Amazon DocumentDB replicas. These replicas should be of the same instance class as the primary instance and in different Availability Zones for your Amazon DocumentDB cluster.

For more information, see the following:
+ [Understanding Amazon DocumentDB cluster fault tolerance](db-cluster-fault-tolerance.md)
+ [Amazon DocumentDB Failover](failover.md)
  + [Controlling the failover target](failover.md#failover-target_control)

### High availability with global clusters
<a name="replication.high-availability.global-clusters"></a>

For high availability across multiple AWS Regions, you can set up [Amazon DocumentDB global clusters](https://docs.aws.amazon.com/documentdb/latest/developerguide/global-clusters.html). Each global cluster spans multiple regions, enabling low latency global reads and disaster recovery from outages across an AWS Region. Amazon DocumentDB automatically handles replicating all data and updates from the primary region to each of the secondary regions.

## Adding replicas
<a name="replication.adding-replicas"></a>

The first instance added to the cluster is the primary instance. Every instance that is added after the first instance is a replica instance. A cluster can have up to 15 replica instances in addition to the primary.

When you create a cluster using the AWS Management Console, a primary instance is automatically created at the same time. To create a replica at the same time as you create the cluster and the primary instance, choose **Create replica in different zone**. For more information, see step 4.d in [Creating an Amazon DocumentDB cluster](db-cluster-create.md). To add more replicas to an Amazon DocumentDB cluster, see [Adding an Amazon DocumentDB instance to a cluster](db-instance-add.md).

When using the AWS CLI to create your cluster, you must explicitly create your primary and replica instances. For more information, see the "Using the AWS CLI" section in the following topics:
+ [Creating an Amazon DocumentDB cluster](db-cluster-create.md)
+ [Adding an Amazon DocumentDB instance to a cluster](db-instance-add.md)

# Amazon DocumentDB Failover
<a name="failover"></a>

In certain cases, such as certain types of planned maintenance, or in the unlikely event of a primary node or Availability Zone failure, Amazon DocumentDB (with MongoDB compatibility) detects the failure and replaces the primary node. During a failover, write down time is minimized. This is because the role of primary node fails over to one of the read replicas instead of having to create and provision a new primary node. This failure detection and replica promotion ensure that you can resume writing to the new primary as soon as promotion is complete.

For failover to function, your cluster must have at least two instances — a primary and at least one replica instance.

**Note**  
This topic only applies to original Amazon DocumentDB instance-based clusters. It does not apply to elastic or global clusters.

## Controlling the failover target
<a name="failover-target_control"></a>

Amazon DocumentDB provides you with failover tiers as a means to control which replica instance is promoted to primary when a failover occurs.

**Failover Tiers**  
Each replica instance is associated with a failover tier (0–15). When a failover occurs due to maintenance or an unlikely hardware failure, the primary instance fails over to a replica with the highest priority (the lowest numbered tier). If multiple replicas have the same priority tier, the primary fails over to that tier's replica that is the closest in size to the previous primary.

By setting the failover tier for a group of select replicas to `0` (the highest priority), you can ensure that a failover will promote one of the replicas in that group. You can effectively prevent specific replicas from being promoted to primary in case of a failover by assigning a low-priority tier (high number) to these replicas. This is useful in cases where specific replicas are receiving heavy use by an application and failing over to one of them would negatively impact a critical application.

You can set the failover tier of an instance when you create it or later by modifying it. Setting an instance failover tier by modifying the instance does not trigger a failover. For more information see the following topics:
+ [Adding an Amazon DocumentDB instance to a cluster](db-instance-add.md)
+ [Modifying an Amazon DocumentDB instance](db-instance-modify.md)

When manually initiating a failover, you have two means to control which replica instance is promoted to primary: the failover tiers as previously described, and the `--target-db-instance-identifier` parameter.

**--`target-db-instance-identifier`**  
For testing, you can force a failover event using the `failover-db-cluster` operation. You can use the `--target-db-instance-identifier` parameter to specify which replica to promote to primary. Using the `--target-db-instance-identifier` parameter supersedes the failover priority tier. If you do not specify the `--target-db-instance-identifier` parameter, the primary failover is in accordance with the failover priority tier.



## What happens during a failover
<a name="failover-what_happens"></a>

Failover is automatically handled by Amazon DocumentDB so that your applications can resume database operations as quickly as possible without administrative intervention.
+ If you have an Amazon DocumentDB replica instance in the same or different Availability Zone when failing over: Amazon DocumentDB flips the canonical name record (CNAME) for your instance to point at the healthy replica, which is, in turn, promoted to become the new primary. Failover typically completes within 30 seconds from start to finish.
+ If you don't have an Amazon DocumentDB replica instance (for example, a single instance cluster): Amazon DocumentDB will attempt to create a new instance in the same Availability Zone as the original instance. This replacement of the original instance is done on a best-effort basis and may not succeed if, for example, there is an issue that is broadly affecting the Availability Zone.

Your application should retry database connections in the event of a connection loss.

## Testing failover
<a name="failover-testing"></a>

A failover for a cluster promotes one of the Amazon DocumentDB replicas (read-only instances) in the cluster to be the primary instance (the cluster writer).

When the primary instance fails, Amazon DocumentDB automatically fails over to an Amazon DocumentDB replica, if one exists. You can force a failover when you want to simulate a failure of a primary instance for testing. Each instance in a cluster has its own endpoint address. Therefore, you need to clean up and re-establish any existing connections that use those endpoint addresses when the failover is complete.

To force a failover, use the `failover-db-cluster` operation with these parameters.
+ `--db-cluster-identifier`—Required. The name of the cluster to fail over.
+ `--target-db-instance-identifier`—Optional. The name of the instance to be promoted to the primary instance.

**Example**  
The following operation forces a failover of the `sample-cluster` cluster. It does not specify which instance to make the new primary instance, so Amazon DocumentDB chooses the instance according to failover tier priority.  
For Linux, macOS, or Unix:  

```
aws docdb failover-db-cluster \
   --db-cluster-identifier sample-cluster
```
For Windows:  

```
aws docdb failover-db-cluster ^
   --db-cluster-identifier sample-cluster
```
The following operation forces a failover of the `sample-cluster` cluster, specifying that `sample-cluster-instance` is to be promoted to the primary role. (Notice `"IsClusterWriter": true` in the output.)  
For Linux, macOS, or Unix:  

```
aws docdb failover-db-cluster \
   --db-cluster-identifier sample-cluster \
   --target-db-instance-identifier sample-cluster-instance
```
For Windows:  

```
aws docdb failover-db-cluster ^
   --db-cluster-identifier sample-cluster ^
   --target-db-instance-identifier sample-cluster-instance
```
Output from this operation looks something like the following (JSON format).  

```
{
    "DBCluster": {
        "HostedZoneId": "Z2SUY0A1719RZT",
        "Port": 27017,
        "EngineVersion": "3.6.0",
        "PreferredMaintenanceWindow": "thu:04:05-thu:04:35",
        "BackupRetentionPeriod": 1,
        "ClusterCreateTime": "2018-06-28T18:53:29.455Z",
        "AssociatedRoles": [],
        "DBSubnetGroup": "default",
        "MasterUsername": "master-user",
        "Engine": "docdb",
        "ReadReplicaIdentifiers": [],
        "EarliestRestorableTime": "2018-08-21T00:04:10.546Z",
        "DBClusterIdentifier": "sample-cluster",
        "ReaderEndpoint": "sample-cluster.node.us-east-1.docdb.amazonaws.com",
        "DBClusterMembers": [
            {
                "DBInstanceIdentifier": "sample-cluster-instance",
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1,
                "IsClusterWriter": true
            },
            {
                "DBInstanceIdentifier": "sample-cluster-instance-00",
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1,
                "IsClusterWriter": false
            },
            {
                "DBInstanceIdentifier": "sample-cluster-instance-01",
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1,
                "IsClusterWriter": false
            }
        ],
        "AvailabilityZones": [
            "us-east-1b",
            "us-east-1c",
            "us-east-1a"
        ],
        "DBClusterParameterGroup": "default.docdb3.6",
        "Endpoint": "sample-cluster.node.us-east-1.docdb.amazonaws.com",
        "IAMDatabaseAuthenticationEnabled": false,
        "AllocatedStorage": 1,
        "LatestRestorableTime": "2018-08-22T21:57:33.904Z",
        "PreferredBackupWindow": "00:00-00:30",
        "StorageEncrypted": false,
        "MultiAZ": true,
        "Status": "available",
        "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster",
        "VpcSecurityGroups": [
            {
                "Status": "active",
                "VpcSecurityGroupId": "sg-12345678"
            }
        ],
        "DbClusterResourceId": "cluster-ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    }
}
```

## Replication lag
<a name="troubleshooting.replication-lag"></a>

Replication lag is typically 50ms or less. The most common reasons for increased replica lag are:
+ A high write rate on the primary that causes the read replicas to fall behind the primary.
+ Contention on the read replicas between long running queries (e.g., large sequential scans, aggregation queries) and incoming write replication.
+ Very large number of concurrent queries on the read replicas.

To minimize replication lag, try these troubleshooting techniques:
+ If you have a high write rate or high CPU utilization, we recommend that you scale up the instances in your cluster.
+ If there are long running queries on your read replicas, and very frequent updates to the documents being queried, consider altering your long running queries, or running them against the primary/write replica to avoid contention on the read replicas.
+ If there is a very large number of concurrent queries or high CPU utilization only on the read replicas, another option is to scale out the number of read replicas to spread out the workload.
+ Because replication lag is a result of high write throughput and long running queries, we recommend troubleshooting the replication lag by utilizing the DBClusterReplicaLagMaximum CW metric in combination with the slow query logger and `WriteThroughput`/`WriteIOPS` metrics.

In general, we recommend that all your replicas are of the same instance type, so that a cluster failover will not cause a degradation in performance.

If you are choosing between scaling up and scaling out (eg. six smaller instances vs three larger instances), we generally recommend trying to scale up first (larger instances) before scaling out, as you will get a larger buffer cache per DB instance.

Proactively, you should set a replication lag alarm and set its threshold to a value that you feel is the upper bound for how far behind (or “stale”) your data on replica instances can be before it starts affecting the functionality of your application. In general, we would advise that the replication lag threshold be exceeded for several data points before alarming, due to transient workloads.

**Note**  
In addition, we recommend that you set another alarm for replication lags that exceed 10 seconds. If you surpass this threshold for multiple data points, we recommend that you scale up your instances or reduce your write throughput on the primary instance.

# Managing Amazon DocumentDB indexes
<a name="managing-indexes"></a>

**Topics**
+ [

## Amazon DocumentDB index creation
](#index-creation)
+ [

## Maintaining Amazon DocumentDB indexes
](#maintaining-indexes)

## Amazon DocumentDB index creation
<a name="index-creation"></a>

Building indexes in Amazon DocumentDB requires a number of decisions to be made: 
+ How quickly does it need to be completed?
+ Can the collection be inaccessible while the build is occurring?
+ How much of an instance's compute power can be allocated to the build?
+ What type of index should be created?

This section helps you answer these questions and provides the commands and monitoring examples to create an Amazon DocumentDB index on your instance-based cluster collection.

### Guidelines
<a name="indexing-guidelines"></a>

The following guidelines include basic limits and configuration tradeoffs when creating new indexes:
+ **Amazon DocumentDB version support** - While single worker indexing is supported on all Amazon DocumentDB versions, multiple worker indexing is supported only on Amazon DocumentDB versions 4.0, 5.0, and 8.0.
+ **Performance trade-off** - Increasing the number of workers in the index creation process increases CPU utilization and read IO on the primary instance of your Amazon DocumentDB database. The resources needed to create a new index will not be available to your running workload.
+ **Elastic clusters** - Parallel indexing is not supported on Amazon DocumentDB elastic clusters.
+ **Maximum workers** - The maximum number of workers you can configure depends on the size of your primary instance in your database cluster. It is half the total number of vCPUs on the primary instance of your database cluster. For example, you can run a maximum of 32 workers on a db.r6g.16xlarge instance that has 64 vCPUs.
**Note**  
Parallel workers are not supported on 2xlarge instance classes and lower.
+ **Minimum workers** - The minimum number of workers you can configure is one. The default setting for index creation on instance-based clusters is two workers. However, you can reduce the number of workers to one by using the “worker threads” option. This will run the process with a single worker.
+ **Index compression** - Amazon DocumentDB doesn't support index compression. Data sizes for indexes might be larger than when you use other options.
+ **Indexing multiple collections** - Half the vCPUs on your database cluster's primary instance can be used for configured workers performing index creation on multiple collections.
+ **Index types** - See [this blog post](https://aws.amazon.com/blogs/database/how-to-index-on-amazon-documentdb-with-mongodb-compatibility/) for a complete explanation of supported index types on Amazon DocumentDB.

### Getting started
<a name="index-build-get-started"></a>

To start index creation on a collection, use the `createIndexes` command. By default, the command will run two parallel workers that increases the speed of the index creation process by two times.

For example, the following command process demonstrates how to create an index for the “user\$1name” field in a document and increase the indexing process speed to four workers:

1. Create indexes using two parallel workers on the cluster:

   ```
   db.runCommand({"createIndexes":"test","indexes":[{"key": {"user_name":1}, "name":"username_idx"}]})
   ```

1. To optimize the speed of the index creation process, you can specify the number of workers by using the “worker threads” option (`"workers":<number>`) in the `db.runCommand createIndexes` command.

   Increase the speed of the process to four parallel workers:

   ```
   db.runCommand({"createIndexes":"test","indexes":[{"key": {"user_name":1}, "name":"username_idx", "workers":4}]})
   ```
**Note**  
The higher the number of workers, the faster the index creation progresses. However, the higher the number of workers increases, the higher the load increases on the vCPUs and read IO of your primary instance. Ensure that your cluster is sufficiently provisioned to handle the increased burden without degrading other workloads.

### Indexing progress status
<a name="index-build-status"></a>

The index creation process works by initializing, scanning collections, sorting keys, and, finally, inserting keys by way of an index builder. The process has up to six stages when you run it in the foreground, and up to nine stages when you run it in the background. You can view status metrics such as percentage completion, total number of scanned storage blocks, sorted keys, and inserted keys on stage by stage basis.

Monitor the progress on the indexing process by using the `db.currentOp()` command in the mongo shell. A 100% completion of the last stage shows that all the indexes have been successfully created:

```
db.currentOp({"command.createIndexes": { $exists : true } })
```

**Note**  
Viewing the indexing progress status is only supported on Amazon DocumentDB 5.0.

#### Index build types
<a name="index-build-types"></a>

The four types of index builds are:
+ **Foreground** — The foreground index build blocks all other database operations until the index is created. The Amazon DocumentDB foreground build is comprised of five stages.
+ **Foreground (unique)** — Single document (unique) foreground index builds block other database operations like regular foreground builds. Unlike the basic foreground build, the unique build uses an additional stage (sorting keys 2) to look for duplicate keys. The foreground (unique) build is comprised of six stages.
+ **Background** — The background index build allows other database operations to run in the foreground while the index is being created. The Amazon DocumentDB background build is comprised of eight stages.
+ **Background (unique)** — Single document (unique) background index builds allow other database operations to run in the foreground while the index is being created. Unlike the basic background build, the unique build uses an additional stage (sorting keys 2) to look for duplicate keys. The background (unique) build is comprised of nine stages.

#### Index build stages
<a name="index-build-stages"></a>


| Stage | Foreground | Foreground (unique) | Background | Background (unique) | 
| --- | --- | --- | --- | --- | 
|  Initializing  |  1  |  1  |  1  |  1  | 
|  building index: initializing  |  2  |  2  |  2  |  2  | 
|  building index: scanning collection  |  3  |  3  |  3  |  3  | 
|  building index: sorting keys 1  |  4  |  4  |  4  |  4  | 
|  building index: sorting keys 2  |    |  5  |    |  5  | 
|  building index: inserting keys  |  5  |  6  |  5  |  6  | 
|  validating: scanning index  |    |    |  6  |  7  | 
|  validating: sorting tuples  |    |    |  7  |  8  | 
|  validating: scanning collection  |    |    |  8  |  9  | 
+ **initializing** - createIndex is preparing the index builder. This phase should be very brief.
+ **building index: initializing** - The index builder is preparing to create the index. This phase should be very brief.
+ **building index: scanning collection** - The index builder is performing a collection scan to collect index keys. The unit of measure is “blocks”.
**Note**  
If more than one worker is configured for the index build, it is displayed in this stage. The “scanning collection” stage is the only stage that uses multiple workers during the index build process. All other stages will display a single worker.
+ **building index: sorting keys 1** - The index builder is sorting the collected index keys. The unit of measure is “keys”.
+ **building index: sorting keys 2** - The index builder is sorting the collected index keys that correspond to dead tuples. This phase only exists for unique index building. The unit of measure is “keys”.
+ **building index: inserting keys** - The index builder is inserting index keys into the new index. The unit of measure is “keys”.
+ **validating: scanning index** - createIndex is scanning the index to find keys that need to be validated. The unit of measure is “blocks”. 
+ **validating: sorting tuples** - createIndex is sorting the output of the index scanning phase.
+ **validating: scanning collection** - createIndex is scanning the collection to validate the index keys found in the previous two phases. The unit of measure is “blocks”.

#### Index build output example
<a name="w2aac35c19b5c13c15"></a>

In the output example below (foreground index build), the status of the index creation is shown. The “msg” field summarizes the build progress by indicating the stage and the completion percentage of the build. The “workers” field indicates the number of workers used during that stage of the index build. The “progress” field shows the actual numbers used to calculate the percentage of completion.

**Note**  
The “currentIndexBuildName”, “msg”, and “progress” fields are not supported on Amazon DocumentDB version 4.0.

```
{
    "inprog" : [{
    … 
        "command": {
            "createIndexes": "test",
            "indexes": [{
                "v": 2,
                "key": {
                    "user_name": 1
                },
                "name": "user_name_1"
            }],
            "lsid": {
                "id": UUID(“094d0fba-8f41-4373-82c3-7c4c7b5ff13b”)
            },
            "$db": "test"
        },
        "currentIndexBuildName": user_name_1,
        "msg": "Index Build: building index number_1, stage 6/6 building index: 656860/1003520 (keys) 65%",
        "workers": 1,
        "progress": {
            "done": 656861,
            "total": 1003520
        },
    … 
    ],
 
    "ok" : 1
}
```

## Maintaining Amazon DocumentDB indexes
<a name="maintaining-indexes"></a>

**Topics**
+ [

### Index bloat
](#db-index-bloat)
+ [

### Index maintenance using `reIndex`
](#reIndex)

### Index bloat
<a name="db-index-bloat"></a>

Amazon DocumentDB uses Multi-Version Concurrency Control (MVCC) to manage concurrent transactions. When documents are deleted or updated, their previous versions remain in collections and indexes as "dead" versions. The garbage collection process automatically reclaims space from these dead versions for future operations.

Index bloat occurs when a collection's indexes become larger due to the accumulation of dead or obsolete index entries or fragmentation within the pages. The percentage reported represents the amount of index space that can be used by future index entries. This bloat consumes space in both the buffer cache and storage. If you want to remove the bloat, you will need to rebuild indexes.

**Example**  
Run the following command to determine unused storage for your index:  

```
db.coll.aggregate({$indexStats:{}});
```
The result looks similar to this:  

```
{ 
    "name" : "_id_",
    "key" : { 
        "_id" : 1 
    },
    "host" : "devbox-test.localhost.a2z.com:27317",
    "size" : NumberLong(827392),
    "accesses" : {
        "ops" : NumberLong(40000),
        "docsRead" : NumberLong(46049),
        "since" : ISODate("2025-04-03T21:44:51.251Z") 
    },
    "cacheStats" : {
        "blksRead" : NumberLong(264),
        "blksHit" : NumberLong(140190),
        "hitRatio" : 99.8121
    }, 
    "unusedStorageSize" : {
        "unusedSizeBytes" : 409600,
        "unusedSizePercent" : 49.51
    }
}
```

You can rebuild indexes without downtime using the `reIndex` command, which requires a scan of the entire collection. See [Index maintenance using `reIndex`](#reIndex).

### Index maintenance using `reIndex`
<a name="reIndex"></a>

`reIndex` is a command used to rebuild an index. It is typically used when an index has become corrupted or inefficient. Over time, indexes can accumulate unused space due to many updates, inserts, or deletes, leading to degraded performance. Reindexing helps to remove such unused space and restore the efficiency of the index.

#### `reIndex` guidelines
<a name="w2aac35c19b7b7b5"></a>
+ `reIndex` is only supported on Amazon DocumentDB 5.0.
+ Amazon DocumentDB supports `reindex` of a single index in the background, allowing for multiple workers. The old index is usable by queries when the `reIndex` process is running.
+ Amazon DocumentDB supports indexing progress report through `currentOp`. You can see index build stages similar to the [Index build stages](#index-build-stages) viewed during index creation. The only difference is that `reIndex` always has eight stages, regardless if it’s unique or not. There’s no “building index: sorting keys 2” stage.
+ `reIndex` can run concurrently with any command except index-related commands on the same collection: `createIndexes`, `dropIndexes`, `collMod`, and `renameCollection`.
+ `reIndex` is currently not supported for text, geospatial, vector, and partial indexes.

##### `reIndex` build
<a name="w2aac35c19b7b7b5b5"></a>

Use the following command to rebuild your index:

```
db.runCommand({ reIndex: "collection-name", index: "index-name"})
```

Optionally, you can also control the number of workers assigned to the rebuild process:

```
db.runCommand({ reIndex: "collection-name", index: "index-name", workers: number })
```

# Managing collection-level document compression
<a name="doc-compression"></a>

Amazon DocumentDB 5.0 collection-level document compression allows you to lower storage and IO costs by compressing the documents in your collections. You can enable document compression at a collection level and view compression metrics as needed by measuring the storage gains through compression metrics such as storage size of compressed documents and compression status. Amazon DocumentDB 5.0 uses the LZ4 compression algorithm to compress documents.

Amazon DocumentDB supports document compression starting with version 5.0. The following are collection-level document compression functions:
+ **Default behavior** — The default compression setting for new collections on a 5.0 cluster is determined by the cluster parameter `default_collection_compression`. This parameter is set to “disabled” by default. 
+ **Compressing existing collections** — The compression setting for existing collections can be changed using the `collMod` command.
+ **Changing the compression threshold** — The default compression threshold is 2KB. This value can be specified for new collections using the `createCollection` command, and changed for existing collections using `collMod` command.

**Note**  
Amazon DocumentDB document compression is not supported on Amazon DocumentDB versions 3.6 and 4.0.

**Topics**
+ [

## Managing document compression
](#manage-compression)
+ [

## Monitoring document compression
](#monitoring-compression)

## Managing document compression
<a name="manage-compression"></a>

### Enabling document compression in a collection
<a name="enabling-collection-compression"></a>

Enable document compression while creating a collection on Amazon DocumentDB 5.0 by using `db.createCollection()` method:

```
db.createCollection( sample_collection,{
    storageEngine : {
        documentDB: {
            compression:{enable: <true | false>}
        }
    }
})
```

### Enabling document compression in a cluster
<a name="enabling-cluster-compression"></a>

Document compression can be enabled by default for all new collections on a cluster level by setting the cluster parameter `default_collection_compression` to “enabled”. When this parameter is set to “enabled”, newly created collections on the cluster will have compression enabled by default with a compression threshold of 2 KB.

### Compressing existing collections
<a name="compress-existing-collections"></a>

You can also modify the compression settings for an existing collection using the `collMod` operation and specifying the following `storageEngine` configuration. Please note that the change made using this command will only apply to newly inserted/updated documents and the compression on previously inserted documents will not change.

```
db.runCommand({ 
    collMod: "orders", 
    storageEngine: { 
        documentDB: {compression: {enable: <true | false>} }
    }
})
```

### Setting the compression thresholds
<a name="set-compression-threshold"></a>

By default, the compression threshold for compressed collections is 2032 bytes. This threshold value can be set in the `createCollection` command when creating a new collection with compression enabled: 

```
db.createCollection( sample_collection, {
    storageEngine : {
        documentDB: {
            compression: {
                enable: true,
                threshold: <128 - 8000>
            }
        }
    }
})
```

You can also modify the compression threshold for an existing compressed collection using the `collMod` operation and specifying the following `storageEngine` configuration:

```
db.runCommand({ 
    collMod: "orders", 
    storageEngine: { 
        documentDB: {
            compression: {
                enable: true,
                threshold: <128 - 8000>
            }
        }
    }
})
```

Please note that the compression threshold can only be set to a value between 128 to 8000 bytes. Additionally, the `enable` option needs to be set to “true” when specifying the compression threshold.

## Monitoring document compression
<a name="monitoring-compression"></a>

You can check if a collection is compressed and calculate it's compression ratio as follows.

View compression statistics by running the `db.printCollectionStats()` or `db.collection.stats()` command from the mongo shell. The output shows you the original size and compressed size that you can compare to analyze the storage gains from document compression. In this example, statistics for a collection named “sample\$1collection” are shown below. A scaling factor of 1024\$11024 is used below to output the `size` and `storageSize` values in MB.

```
db.sample_collection.stats(1024*1024)
```

The following is an example of the output for the above command:

```
{
    "ns" : "test.sample_collection",
    "count" : 1000000,
    "size" : 3906.3,
    "avgObjSize" : 4096,
    "storageSize" : 1953.1, 
    compression:{"enabled" : true,"threshold" : 2032},
    ...
}
```
+ **size** - The original size of the document collection.
+ **avgObjSize** - The average document size before compression rounded off to first decimal. The unit of measure is bytes.
+ **storageSize** - The storage size of the collection after compression. The unit of measure is bytes.
+ **enabled** - Indicates if compression is enabled or disabled.

To calculate the actual compression ratio, divide the collection size by the storage size (size/storageSize). For the example above, the calculation is 3906.3/1953.1 which translates to a 2:1 compression ratio.

# Managing dictionary-based compression in Amazon DocumentDB 8.0
<a name="dict-compression"></a>

Amazon DocumentDB 8.0 introduces a new document compression algorithm, zstd, as an improved alternative to LZ4. When you enable dictionary compression on a Amazon DocumentDB 8.0 collection by selecting Zstd as the compression algorithm, documents from your collection are sampled to create a custom compression dictionary. New and updated documents are compressed using this dictionary and the zstd algorithm. This approach typically achieves higher compression ratios than standard compression methods, especially for collections with consistent document schemas or repeated field names. 

Lz4 is an algorithm designed for fast compression and decompression. It is known to be light on the CPU while achieving noticeable compression. Zstd is a general-purpose algorithm that with default settings uses more CPU but achieves better compression ratios than lz4. The usage of dictionaries improves compression even further for most JSON documents. Some benefits of Zstd algorithm are:
+ Reduced Storage Costs: Higher compression ratios mean less storage usage and lower costs.
+ Lower I/O: Compressed documents require less I/O, potentially improving performance.
+ Optimized for your collection: The dictionary is trained specifically for your collection's data patterns.

**Note**  
Dictionary-based compression is not supported on Amazon DocumentDB versions 3.6, 4.0, and 5.0.

## Performance Considerations
<a name="perf-considerations"></a>

Zstd compression involves the following trade-offs: 
+ Storage vs. CPU: Zstd compression achieves better compression ratios but may use slightly more CPU resources compared to LZ4 compression.
+ Initial Compression: New collections may not achieve optimal compression until enough documents are inserted to train an effective dictionary. Currently, a dictionary is trained if the collection at least 100 documents.
+ Workload Type: Read-intensive workloads where the entire data fits into the buffer cache may experience an increase in latency and CPU usage due to decompression overhead.

Zstd compression is particularly effective for collections with small documents, document arrays and repeated field names.

## Enabling dictionary-based compression
<a name="enabling-zstd"></a>

For new collections you can use the below command to enable Zstd compression: 

```
db.createCollection("myCollection", 
    { 
        storageEngine: { 
            documentDB: { 
                compression: {
                    enable: true,
                    algorithm: "zstd"
                } 
            }
        }
    }
 )
```

You can also enable or modify compression on an existing collection: 

```
db.runCommand({ 
    collMod: "myCollection", 
    storageEngine: { 
        documentDB: { 
            compression: {
                enable: true,
                algorithm: "zstd"
            } 
        }
    }
 })
```

To enable Zstd algorithm across all collections on your cluster, you can modify the cluster parameter group to select “zstd” as the value for the parameter “default\$1collection\$1compression”.

## Getting Started
<a name="getting-started"></a>

Amazon DocumentDB 8.0 comes with Zstd compression turned ON by default. You can always turn it OFF by setting the value of ‘default\$1compression’ to disabled in your cluster parameter group. It must be noted that starting with Amazon DocumentDB 8.0, ‘enabled’ is no longer a valid choice for default\$1compression, and you must select from Zstd and LZ4. 

## Monitoring
<a name="monitoring"></a>

You can view compression information for a collection using one of the following commands:
+ db.runCommand(\$1 collStats: "myCollection" \$1) OR
+ db.collection.stats()

These commands return key statistics that you can use to compute compression ratio:
+ compression.algorithm: The algorithm used ("lz4" or "zstd")
+ storageSize: The actual storage used by the collection, after compression. Note that this number includes fragmentation (that is, the unused space in database pages)
+ avgObjSize: The average logical size of the collection's documents, decompressed. Note that if your collection has more than 20k documents, this number will be an approximation based on a sample of 20k documents.
+ size: The logical size of the collection without compression. This number is obtained by multiplying avgObjSize by the total number of documents in the collection, so if avgObjSize is an approximation, this number will also be an approximation.
+ count: Number of documents in the collection 

The following CloudWatch metrics can be helpful while evaluating dictionary-based compression:
+ CPUUtilization
+ FreeableMemory
+ VolumeBytesUsed
+ VolumeReadIOPs
+ VolumeWriteIOPs

collStats metrics:
+ storageSize
+ size

In addition, it can be useful to keep track of metrics specific to your application, like latency and throughput per query type or API.

# Managing Amazon DocumentDB events
<a name="managing-events"></a>

Amazon DocumentDB (with MongoDB compatibility) keeps a record of events that relate to your clusters, instances, snapshots, security groups, and cluster parameter groups. This information includes the date and time of the event, the source name and source type of the event, and a message that is associated with the event.

**Important**  
For certain management features, Amazon DocumentDB uses operational technology that is shared with Amazon RDS and Amazon Neptune. Region limits, limits that are governed at the Region level, are shared between Amazon DocumentDB, Amazon RDS, and Amazon Neptune. For more information, see [Regional quotas](limits.md#limits-regional_quotas).

**Topics**
+ [

## Viewing Amazon DocumentDB event categories
](#viewing-event-categories)
+ [

## Viewing Amazon DocumentDB events
](#viewing-events)

## Viewing Amazon DocumentDB event categories
<a name="viewing-event-categories"></a>

Each Amazon DocumentDB resource type has specific types of events that can be associated with it. You can use the AWS CLI `describe-event-categories` operation to view the mapping between event types and Amazon DocumentDB resource types.

**Parameters**
+ **--source-type**—Optional. Use the `--source-type` parameter to see the event categories for a particular source type. The following are permitted values:
  + `db-cluster`
  + `db-instance`
  + `db-parameter-group`
  + `db-security-group`
  + `db-cluster-snapshot`
+ **--filters**—Optional. To view the event categories for just Amazon DocumentDB, use the filter `--filter Name=engine,Values=docdb`.

**Example**  
The following code lists the event categories associated with clusters.  
For Linux, macOS, or Unix:  

```
aws docdb describe-event-categories \
    --filter Name=engine,Values=docdb \
    --source-type db-cluster
```
For Windows:  

```
aws docdb describe-event-categories ^
    --filter Name=engine,Values=docdb ^
    --source-type db-cluster
```
Output from this operation looks something like the following (JSON format).  

```
{
    "EventCategoriesMapList": [
        {
            "EventCategories": [
                "notification",
                "failure",
                "maintenance",
                "failover"
            ],
            "SourceType": "db-cluster"
        }
    ]
}
```
The following code lists the event categories that are associated with each Amazon DocumentDB source type.  

```
aws docdb describe-event-categories
```
Output from this operation looks something like the following (JSON format).  

```
{
    "EventCategoriesMapList": [
        {
            "SourceType": "db-instance",
            "EventCategories": [
                "notification",
                "failure",
                "creation",
                "maintenance",
                "deletion",
                "recovery",
                "restoration",
                "configuration change",
                "read replica",
                "backtrack",
                "low storage",
                "backup",
                "availability",
                "failover"
            ]
        },
        {
            "SourceType": "db-security-group",
            "EventCategories": [
                "configuration change",
                "failure"
            ]
        },
        {
            "SourceType": "db-parameter-group",
            "EventCategories": [
                "configuration change"
            ]
        },
        {
            "SourceType": "db-cluster",
            "EventCategories": [
                "notification",
                "failure",
                "maintenance",
                "failover"
            ]
        },
        {
            "SourceType": "db-cluster-snapshot",
            "EventCategories": [
                "backup"
            ]
        }
    ]
}
```

## Viewing Amazon DocumentDB events
<a name="viewing-events"></a>

You can retrieve events for your Amazon DocumentDB resources through the Amazon DocumentDB console, which shows events from the past 24 hours. You can also retrieve events for your Amazon DocumentDB resources by using the [describe-events](https://docs.aws.amazon.com/cli/latest/reference/docdb/describe-events.html) AWS CLI command, or the [DescribeEvents](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DescribeEvents.html) Amazon DocumentDB API operation. If you use the AWS CLI or the Amazon DocumentDB API to view events, you can retrieve events for up to the past 14 days.

------
#### [ Using the AWS Management Console ]

**To view all Amazon DocumentDB instance events for the past 24 hours**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Events**. The available events appear in a list.

1. Use the **Filter** list to filter the events by type. Enter a term in the text box to further filter your results. For example, the following screenshot shows filtering all Amazon DocumentDB events for *snapshot* events.  
![\[Screenshot of the events section showing filtering events for snapshots.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/events-filtering.png)

------
#### [ Using the AWS CLI ]

**To view all Amazon DocumentDB instance events for the past 7 days**  
You can view all Amazon DocumentDB instance events for the past 7 days by running the [describe-events](https://docs.aws.amazon.com/cli/latest/reference/docdb/describe-events.html) AWS CLI operation with the `--duration` parameter set to `10080` (10,080 minutes).

```
aws docdb describe-events --duration 10080
```

**Filtering for Amazon DocumentDB Events**

To see specific Amazon DocumentDB events, use the `describe-events` operation with the following parameters.

**Parameters**
+ **--filter**—Required to limit returned values to Amazon DocumentDB events. Use **Name=engine,Values=docdb** to filter all events for Amazon DocumentDB only.
+ **--source-identifier**—Optional. The identifier of the event source for which events are returned. If omitted, events from all sources are included in the results.
+ **--source-type**—Optional, unless `--source-identifier` is provided, then required. If `--source-identifier` is provided, `--source-type` must agree with the type of the `--source-identifier`. The following are permitted values:
  + `db-cluster`
  + `db-instance`
  + `db-parameter-group`
  + `db-security-group`
  + `db-cluster-snapshot`

The following example lists all your Amazon DocumentDB events.

```
aws docdb describe-events --filters Name=engine,Values=docdb
```

Output from this operation looks something like the following (JSON format).

```
{
    "Events": [
        {
            "SourceArn": "arn:aws:rds:us-east-1:123SAMPLE012:db:sample-cluster-instance3",
            "Message": "instance created",
            "SourceType": "db-instance",
            "Date": "2018-12-11T21:17:40.023Z",
            "SourceIdentifier": "sample-cluster-instance3",
            "EventCategories": [
                "creation"
            ]
        },
        {
            "SourceArn": "arn:aws:rds:us-east-1:123SAMPLE012:db:docdb-2018-12-11-21-08-23",
            "Message": "instance shutdown",
            "SourceType": "db-instance",
            "Date": "2018-12-11T21:25:01.245Z",
            "SourceIdentifier": "docdb-2018-12-11-21-08-23",
            "EventCategories": [
                "availability"
            ]
        },
        {
            "SourceArn": "arn:aws:rds:us-east-1:123SAMPLE012:db:docdb-2018-12-11-21-08-23",
            "Message": "instance restarted",
            "SourceType": "db-instance",
            "Date": "2018-12-11T21:25:11.441Z",
            "SourceIdentifier": "docdb-2018-12-11-21-08-23",
            "EventCategories": [
                "availability"
            ]
        }
    ]
}
```

------

For more information, see [Auditing Amazon DocumentDB events](event-auditing.md).

# Choosing regions and availability zones
<a name="regions-and-azs"></a>

Amazon cloud computing resources are hosted in multiple locations worldwide. These locations consist of AWS Regions and Availability Zones. Each *AWS Region* is a separate geographic area. Each Region has multiple, isolated locations known as *Availability Zones*. Amazon DocumentDB provides you the ability to place resources, such as instances, and data in multiple locations. Resources aren't replicated across AWS Regions unless you do so specifically.

Amazon operates advanced, highly available data centers. Although rare, failures can occur that affect the availability of instances that are in the same location. If you host all your instances in a single location that is affected by such a failure, none of your instances would be available. The following diagram shows an AWS Region with three Availability Zones.

![\[A diagram of a Region containing three Availability Zones a, b, and c.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/RegionsAndAZs.png)


It is important to remember that each Region is independent. Any Amazon DocumentDB activity that you initiate (for example, creating instances or listing available instances) runs only in your current default AWS Region. You can change the default Region on the console by setting the `EC2_REGION` environment variable. Or you can override it by using the `--region` parameter in the AWS CLI. For more information, see [Configuring the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html), specifically, the sections on environment variables and command line options. 

When you create a cluster using the Amazon DocumentDB console, and you choose to create a replica in a different Availability Zone, Amazon DocumentDB creates two instances. It creates the primary instance in one Availability Zone and the replica instance in a different Availability Zone. The cluster volume is always replicated across three Availability Zones.

To create or work with an Amazon DocumentDB instance in a specific AWS Region, use the corresponding regional service endpoint. 

## Region availability
<a name="regions-and-azs-availability"></a>

Amazon DocumentDB is available in the following AWS Regions. 

**Regions supported by Amazon DocumentDB**


| Region Name | Region | Availability Zones (compute) | 
| --- | --- | --- | 
| US East (Ohio) | `us-east-2` | 3 | 
| US East (N. Virginia) | `us-east-1` | 6 | 
| US West (Oregon) | `us-west-2` | 4 | 
| Africa (Cape Town) | `af-south-1` | 3 | 
| South America (São Paulo) | `sa-east-1` | 3 | 
| Asia Pacific (Hong Kong) | `ap-east-1` | 3 | 
| Asia Pacific (Hyderabad) | `ap-south-2` | 3 | 
| Asia Pacific (Malaysia) | `ap-southeast-5` | 3 | 
| Asia Pacific (Mumbai) | `ap-south-1` | 3 | 
| Asia Pacific (Osaka) | `ap-northeast-3` | 3 | 
| Asia Pacific (Seoul) | `ap-northeast-2` | 4 | 
| Asia Pacific (Singapore) | `ap-southeast-1` | 3 | 
| Asia Pacific (Sydney) | `ap-southeast-2` | 3 | 
| Asia Pacific (Jakarta) | `ap-southeast-3` | 3 | 
| Asia Pacific (Melbourne) | `ap-southeast-4` | 3 | 
| Asia Pacific (Thailand) | `ap-southeast-7` | 3 | 
| Asia Pacific (Tokyo) | `ap-northeast-1` | 3 | 
| Canada (Central) | `ca-central-1` | 3 | 
| China (Beijing) Region | `cn-north-1` | 3 | 
| China (Ningxia) | `cn-northwest-1` | 3 | 
| Europe (Frankfurt) | `eu-central-1` | 3 | 
| Europe (Zurich) | `eu-central-2` | 3 | 
| Europe (Ireland) | `eu-west-1` | 3 | 
| Europe (London) | `eu-west-2` | 3 | 
| Europe (Milan) | `eu-south-1` | 3 | 
| Europe (Paris) | `eu-west-3` | 3 | 
| Europe (Spain) | `eu-south-2` | 3 | 
| Europe (Stockholm) | `eu-north-1` | 3 | 
| Mexico (Central) | `mx-central-1` | 3 | 
| Middle East (UAE) | `me-central-1` | 3 | 
| Israel (Tel Aviv) | `il-central-1` | 3 | 
| AWS GovCloud (US-West) | `us-gov-west-1` | 3 | 
| AWS GovCloud (US-East) | `us-gov-east-1` | 3 | 

By default, the time zone for an Amazon DocumentDB cluster is Universal Time Coordinated (UTC).

For information on finding the connection endpoints for clusters and instances in a particular region, see [Understanding Amazon DocumentDB endpoints](endpoints.md).

# Managing Amazon DocumentDB cluster parameter groups
<a name="cluster_parameter_groups"></a>

You can manage Amazon DocumentDB engine configuration by using parameters in a cluster parameter group. A *cluster parameter group* is a collection of Amazon DocumentDB configuration values that make it easier to manage the parameters of your Amazon DocumentDB clusters. Cluster parameter groups act as a container for engine configuration values that are applied to all instances in the cluster. 

This section describes how to create, view, and modify cluster parameter groups. It also shows how you can determine which cluster parameter group is associated with a given cluster.

**Topics**
+ [Describing cluster parameter groups](cluster_parameter_groups-describe.md)
+ [Creating cluster parameter groups](cluster_parameter_groups-create.md)
+ [Modifying cluster parameter groups](cluster_parameter_groups-modify.md)
+ [Modifying clusters to use customized cluster parameter groups](cluster_parameter_groups-modify_clusters.md)
+ [Copying cluster parameter groups](cluster_parameter_groups-copy.md)
+ [Resetting cluster parameter groups](cluster_parameter_groups-reset.md)
+ [Deleting cluster parameter groups](cluster_parameter_groups-delete.md)
+ [Cluster parameters reference](cluster_parameter_groups-list_of_parameters.md)

# Describing Amazon DocumentDB cluster parameter groups
<a name="cluster_parameter_groups-describe"></a>

A `default` cluster parameter group is created automatically when you create the first Amazon DocumentDB cluster in new region or are using a new engine. Subsequent clusters, which are created in the same region and have the same engine version, are created with the `default` cluster parameter group.

**Topics**
+ [Describing the details of a cluster parameter group](#cluster_parameter_groups-describe_details)
+ [Determining a cluster's parameter group](#cluster_parameter_groups-determine)
+ [Determining clusters and instances associated with a cluster parameter group](#cluster_parameter_groups-count)

## Describing the details of an Amazon DocumentDB cluster parameter group
<a name="cluster_parameter_groups-describe_details"></a>

To describe the details of a given cluster parameter group, complete the following steps using the AWS Management Console or the AWS Command Line Interface (AWS CLI).

------
#### [ Using the AWS Management Console ]

****

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Parameter groups**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the **Cluster parameter groups** pane, select the name of the parameter group that you want to see the details of.

1. The resulting page shows the parameter group's parameters, recent activity, and tags.
   + Under **Cluster parameters**, you can see the parameter's name, current value, allowed values, whether the parameter is modifiable, its apply type, data type, and description. You can modify individual parameters by selecting the parameter and then choosing **Edit** in the **Cluster parameters** section. For more information, see [Modifying Amazon DocumentDB cluster parameters](cluster_parameter_groups-parameters.md).
   + Under **Recent events**, you can see the most recent events for this parameter group. You can filter through these events using the search bar in this section. For more information, see [Managing Amazon DocumentDB events](managing-events.md).
   + Under **Tags**, you can see the tags that are on this cluster parameter group. You can add or remove tags by choosing **Edit** in the **Tags** section. For more information, see [Tagging Amazon DocumentDB resources](tagging.md).

------
#### [ Using the AWS CLI ]

You can use the `describe-db-cluster-parameter-groups` AWS CLI command to view the Amazon Resource Name (ARN), family, description, and name of a single cluster parameter group or all cluster parameter groups that you have for Amazon DocumentDB. You can also use the `describe-db-cluster-parameters` AWS CLI command to view the parameters and their details inside a single cluster parameter group.
+ **--describe-db-cluster-parameter-groups** — To see a listing of all your cluster parameter groups and their details.
  + **--db-cluster-parameter-group-name** — Optional. The name of the cluster parameter group that you want described. If this parameter is omitted, all cluster parameter groups are described.
+ **--describe-db-cluster-parameters** — To list all the parameters inside a parameter group and their values.
  + **--db-cluster-parameter-group name** — Required. The name of the cluster parameter group that you want described.

**Example**  
The following code lists up to 100 cluster parameter groups and their ARN, family, description, and name.  

```
aws docdb describe-db-cluster-parameter-groups
```
Output from this operation looks something like the following (JSON format).  

```
{
          "DBClusterParameterGroups": [
              {
                  "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:012345678912:cluster-pg:default.docdb4.0",
                  "DBParameterGroupFamily": "docdb4.0",
                  "Description": "Default cluster parameter group for docdb4.0",
                  "DBClusterParameterGroupName": "default.docdb4.0"
              },
              {
                  "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:012345678912:cluster-pg:sample-parameter-group",
                  "DBParameterGroupFamily": "docdb4.0",
                  "Description": "Custom docdb4.0 parameter group",
                  "DBClusterParameterGroupName": "sample-parameter-group"
              }
          ]
}
```

**Example**  
The following code lists the ARN, family, description, and name for `sample-parameter-group`.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-cluster-parameter-groups \
          --db-cluster-parameter-group-name sample-parameter-group
```
For Windows:  

```
aws docdb describe-db-cluster-parameter-groups ^
          --db-cluster-parameter-group-name sample-parameter-group
```
Output from this operation looks something like the following (JSON format).  

```
{
          "DBClusterParameterGroups": [
              {
                  "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:cluster-pg:sample-parameter-group",
                  "Description": "Custom docdb4.0 parameter group",
                  "DBParameterGroupFamily": "docdb4.0",
                  "DBClusterParameterGroupName": "sample-parameter-group"
              }
          ]
}
```

**Example**  
The following code lists the values of the parameters in `sample-parameter-group`.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-cluster-parameters \
    --db-cluster-parameter-group-name sample-parameter-group
```
For Windows:  

```
aws docdb describe-db-cluster-parameters ^
    --db-cluster-parameter-group-name sample-parameter-group
```
Output from this operation looks something like the following (JSON format).  

```
{
   "Parameters": [
         {
            "ParameterName": "audit_logs",
            "ParameterValue": "disabled",
            "Description": "Enables auditing on cluster.",
            "Source": "system",
            "ApplyType": "dynamic",
            "DataType": "string",
            "AllowedValues": "enabled,disabled",
            "IsModifiable": true,
            "ApplyMethod": "pending-reboot"
         },
         {
            "ParameterName": "change_stream_log_retention_duration",
            "ParameterValue": "17777",
            "Description": "Duration of time in seconds that the change stream log is retained and can be consumed.",
            "Source": "user",
            "ApplyType": "dynamic",
            "DataType": "integer",
            "AllowedValues": "3600-86400",
            "IsModifiable": true,
            "ApplyMethod": "pending-reboot"
         }
   ]
}
```

------

## Determining an Amazon DocumentDB cluster's parameter group
<a name="cluster_parameter_groups-determine"></a>

To determine which parameter group is associated with a particular cluster, complete the following steps using the AWS Management Console or the AWS CLI. 

------
#### [ Using the AWS Management Console ]

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the left navigation pane, choose **Clusters**.

1. In the list of clusters, select the name of the cluster you are interested in.

1. The resulting page shows the details of the cluster that you selected. Scroll down to **Cluster details**. At the bottom of that section, locate the parameter group's name below **Cluster parameter group**.  
![\[Screenshot: Showing a cluster's parameter group.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-determine-parameter-group.png)

------
#### [ Using the AWS CLI ]

The following AWS CLI code determines which parameter group is governing the cluster `sample-cluster`.

```
aws docdb describe-db-clusters \
      --db-cluster-identifier sample-cluster \
      --query 'DBClusters[*].[DBClusterIdentifier,DBClusterParameterGroup]'
```

Output from this operation looks something like the following (JSON format).

```
[
       [
           "sample-cluster",
           "sample-parameter-group"
       ]
]
```

------

## Determining clusters and instances associated with a Amazon DocumentDB cluster parameter group
<a name="cluster_parameter_groups-count"></a>

To determine how many clusters and instances are associated with each parameter group, complete the following steps using the AWS CLI.

------
#### [ Using the AWS CLI ]

The following AWS CLI code determines how many clusters and instances are associated with `sample-parameter-group`.

For Linux, macOS, or Unix:

```
aws docdb describe-db-clusters \
      --query 'DBClusters[*].[DBClusterParameterGroup,DBClusterIdentifier,DBClusterMembers[*].DBInstanceIdentifier]' \
      --output json | \
      jq -r 'group_by(.[0]) | map({
         parameter_group_name: .[0][0],
         total_clusters: length,
         total_instances: map(.[2] | length) | add // 0
      }) | .[]'
```

For Windows:

```
aws docdb describe-db-clusters ^
      --query 'DBClusters[*].[DBClusterParameterGroup,DBClusterIdentifier,DBClusterMembers[*].DBInstanceIdentifier]' ^
      --output json | ^
      jq -r 'group_by(.[0]) | map({
         parameter_group_name: .[0][0],
         total_clusters: length,
         total_instances: map(.[2] | length) | add // 0
      }) | .[]'
```

Output from this operation looks something like the following (JSON format).

```
{
   "parameter_group_name": "sample-parameter-group",
   "total_clusters": 50,
   "total_instances": 150
}
```

------

# Creating Amazon DocumentDB cluster parameter groups
<a name="cluster_parameter_groups-create"></a>

Default cluster parameter groups such as `default.docdb5.0`, `default.docdb4.0`, or `default.docdb3.6`, are created when you create a cluster with a new engine version and in a new region. Subsequent clusters created in this region and with the same engine version inherit the `default` cluster parameter group. Once created, the `default` parameter groups cannot be deleted or renamed. You can modify the engine behavior of cluster instances by creating a custom parameter group with preferred parameter values and attaching it to your Amazon DocumentDB cluster. 

The following procedure guides you through creating a custom cluster parameter group. You can then [modify the parameters within that parameter group](https://docs.aws.amazon.com//documentdb/latest/developerguide/cluster_parameter_groups-modify.html).

**Note**  
After you create a cluster parameter group, you should wait at least 5 minutes before using that particular parameter group. This allows Amazon DocumentDB to fully complete the `create` action before the cluster parameter group is used for a new cluster. You can use the AWS Management Console or the `describe-db-cluster-parameter-groups` AWS CLI operation to verify that your cluster parameter group has been created. For more information, see [Describing Amazon DocumentDB cluster parameter groups](cluster_parameter_groups-describe.md).

------
#### [ Using the AWS Management Console ]

**To create a cluster parameter group**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Parameter groups**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the **Cluster parameter groups** pane, choose **Create**.

1. In the **Create cluster parameter group** pane, enter the following:

   1. **New cluster parameter group name** — Enter a name for the cluster parameter group. For example, `sample-parameter-group`. Cluster parameter groups have the following naming constraints:
      + Length is [1–255] alphanumeric characters.
      + First character must be a letter.
      + Cannot end with a hyphen or contain two consecutive hyphens.

   1. **Family** — Choose a DocumentDB version you intend to use for your cluster.

   1. **Description** — Provide a description for this cluster parameter group.

1. To create the cluster parameter group, choose **Create**. To cancel the operation, choose **Cancel**.

1. After you choose **Create**, the following text appears at the top of the page to verify that your cluster parameter group has been successfully created:

   ```
   Successfully created cluster parameter group 'sample-parameter-group'.
   ```

------
#### [ Using the AWS CLI ]

To create a new cluster parameter group for Amazon DocumentDB 4.0 clusters, use the AWS CLI `create-db-cluster-parameter-group` operation with the following parameters:
+ **--db-cluster-parameter-group-name** — The name of the custom cluster parameter group. For example, `sample-parameter-group`.
+ **--db-cluster-parameter-group-family** — The cluster parameter group family that is used as the template for the custom cluster parameter group.
+ **--description** — The user-provided description for this cluster parameter group. The following example uses "`Custom docdb4.0 parameter group`".

For Linux, macOS, or Unix:

**Example**  

```
aws docdb create-db-cluster-parameter-group \
 --db-cluster-parameter-group-name sample-parameter-group \
 --db-parameter-group-family docdb5.0 \
 --description "Custom docdb5.0 parameter group"
```
For Windows:  

```
aws docdb create-db-cluster-parameter-group ^
 --db-cluster-parameter-group-name sample-parameter-group ^
 --db-parameter-group-family docdb5.0 ^
 --description "Custom docdb5.0 parameter group"
```
Output from this operation looks something like the following (JSON format).  

```
{
    "DBClusterParameterGroup": {
        "DBClusterParameterGroupName": "sample-parameter-group",
        "DBParameterGroupFamily": "docdb5.0",
        "Description": "Custom docdb4.0 parameter group",
        "DBClusterParameterGroupArn": "sample-parameter-group-arn"
    }
}
```

------

# Modifying Amazon DocumentDB cluster parameter groups
<a name="cluster_parameter_groups-modify"></a>

This section explains how to modify a *custom* Amazon DocumentDB parameter group. In Amazon DocumentDB, you cannot modify a `default` cluster parameter group which is created when you first create a cluster with new engine version in a new region. If your Amazon DocumentDB cluster is using the default cluster parameter group and you want to modify a value in it, you must first [create a new parameter group](https://docs.aws.amazon.com//documentdb/latest/developerguide/cluster_parameter_groups-create.html) or [copy an existing parameter group](https://docs.aws.amazon.com//documentdb/latest/developerguide/cluster_parameter_groups-copy.html), modify it, and then apply the modified parameter group to your cluster.

Complete the following steps to modify a custom cluster parameter group. Modify actions could take a while to propagate. Please wait for the modified cluster paramater group to be available before attaching it to your cluster. You can use the AWS Management Console or the AWS CLI `describe-db-cluster-parameters` operation to verify that your cluster parameter group has been modified. For more information, see [Describing cluster parameter groups](cluster_parameter_groups-describe.md).

------
#### [ Using the AWS Management Console ]

Follow these steps to modify a custom Amazon DocumentDB parameter group. You can't modify a `default` parameter group. If you want to modify a value in the `default` parameter group, you can [copy the default cluster parameter group](https://docs.aws.amazon.com//documentdb/latest/developerguide/cluster_parameter_groups-copy.html), modify it, and then apply the modified parameter group to your cluster. For more information about applying parameter groups to your cluster, see [Modifying an Amazon DocumentDB cluster](db-cluster-modify.md).

**To modify a custom cluster parameter group**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane on the left side of the console, choose **Parameter groups**. In the list of parameter groups, choose the name of the parameter group that you want to modify.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. For each parameter in the parameter group that you want to modify, do the following:

   1. Locate the parameter that you want to modify, and verify that it is modifiable by checking if it is listed as `true` under the **Modifiable** column.

   1. If it is modifiable, select the parameter and choose **Edit** from the top right of the console page.

   1. In the **Modify `<parameter-name>`** dialog box, make the changes that you want. Then choose **Modify cluster parameter**, or choose **Cancel** to discard the changes.

------
#### [ Using the AWS CLI ]

You can modify the `ParameterValue`, `Description`, or `ApplyMethod` of any modifiable parameter in a custom Amazon DocumentDB cluster parameter group using the AWS CLI. You can't make modifications directly to a default cluster parameter group.

To modify a custom cluster parameter group's parameters, use the `modify-db-cluster-parameter-group` operation with the following parameters.
+ **--db-cluster-parameter-group-name** — Required. The name of the cluster parameter group that you are modifying.
+ **--parameters** — Required. The parameters that you are modifying. For a list of the parameters that apply to all instances in an Amazon DocumentDB cluster, see the [Amazon DocumentDB cluster parameters reference](cluster_parameter_groups-list_of_parameters.md). Each parameter entry must include the following:
  + **ParameterName** — The name of the parameter that you are modifying.
  + **ParameterValue** — The new value for this parameter.
  + **ApplyMethod** — How you want changes to this parameter applied. Permitted values are `immediate` and `pending-reboot`.
**Note**  
Parameters with the `ApplyType` of `static` must have an `ApplyMethod` of `pending-reboot`.

**Example - Modifying a parameter's value**  
In this example, you list the parameter values of `sample-parameter-group` and modify the `tls` parameter. Then, after waiting 5 minutes, you again list the parameter values of `sample-parameter-group` to see the changed parameter values.  

1. List the parameters and their values of `sample-parameter-group`.

   For Linux, macOS, or Unix:

   ```
   aws docdb describe-db-cluster-parameters \
          --db-cluster-parameter-group-name sample-parameter-group
   ```

   For Windows:

   ```
   aws docdb describe-db-cluster-parameters ^
          --db-cluster-parameter-group-name sample-parameter-group
   ```

   Output from this operation looks something like the following (JSON format).

   ```
   {
          "Parameters": [
              {
                  "Source": "system",
                  "ApplyType": "static",
                  "AllowedValues": "disabled,enabled",
                  "ParameterValue": "enabled",
                  "ApplyMethod": "pending-reboot",
                  "DataType": "string",
                  "ParameterName": "tls",
                  "IsModifiable": true,
                  "Description": "Config to enable/disable TLS"
              },
              {
                  "Source": "user",
                  "ApplyType": "dynamic",
                  "AllowedValues": "disabled,enabled",
                  "ParameterValue": "enabled",
                  "ApplyMethod": "pending-reboot",
                  "DataType": "string",
                  "ParameterName": "ttl_monitor",
                  "IsModifiable": true,
                  "Description": "Enables TTL Monitoring"
              }
          ]
   }
   ```

1. Modify the `tls` parameter so that its value is `disabled` . 

   You can't modify the `ApplyMethod` because the `ApplyType` is `static`. 

   For Linux, macOS, or Unix:

   ```
   aws docdb modify-db-cluster-parameter-group \
          --db-cluster-parameter-group-name sample-parameter-group \
          --parameters "ParameterName"=tls,"ParameterValue"=disabled,"ApplyMethod"=pending-reboot
   ```

   For Windows:

   ```
   aws docdb modify-db-cluster-parameter-group ^
          --db-cluster-parameter-group-name sample-parameter-group ^
          --parameters "ParameterName"=tls,"ParameterValue"=disabled,"ApplyMethod"=pending-reboot
   ```

   Output from this operation looks something like the following (JSON format).

   ```
   {
          "DBClusterParameterGroupName": "sample-parameter-group"
      }
   ```

1. Wait at least 5 minutes.

1. List the parameter values of `sample-parameter-group` to verify that the `tls` parameter was modified.

   For Linux, macOS, or Unix:

   ```
   aws docdb describe-db-cluster-parameters \
          --db-cluster-parameter-group-name sample-parameter-group
   ```

   For Windows:

   ```
   aws docdb describe-db-cluster-parameters ^
          --db-cluster-parameter-group-name sample-parameter-group
   ```

   Output from this operation looks something like the following (JSON format).

   ```
   {
          "Parameters": [
              {
                  "ParameterValue": "false",
                  "ParameterName": "enable_audit_logs",
                  "ApplyType": "dynamic",
                  "DataType": "string",
                  "Description": "Enables auditing on cluster.",
                  "AllowedValues": "true,false",
                  "Source": "system",
                  "IsModifiable": true,
                  "ApplyMethod": "pending-reboot"
              },
              {
                  "ParameterValue": "disabled",
                  "ParameterName": "tls",
                  "ApplyType": "static",
                  "DataType": "string",
                  "Description": "Config to enable/disable TLS",
                  "AllowedValues": "disabled,enabled",
                  "Source": "system",
                  "IsModifiable": true,
                  "ApplyMethod": "pending-reboot"
              }
          ]
   }
   ```

------

# Modifying Amazon DocumentDB clusters to use custom cluster parameter groups
<a name="cluster_parameter_groups-modify_clusters"></a>

When you create an Amazon DocumentDB cluster, a `default.docdb4.0` parameter group is automatically created for that cluster. You can't modify the `default` cluster parameter group. Instead, you can modify your Amazon DocumentDB cluster to associate a new customized parameter group with it. 

This section explains how to modify an existing Amazon DocumentDB cluster to use a custom cluster parameter group using the AWS Management Console and the AWS Command Line Interface (AWS CLI). 

------
#### [ Using the AWS Management Console ]

**To modify an Amazon DocumentDB cluster to use a new, non-default cluster parameter group**

1. Before you begin, make sure you have created an Amazon DocumentDB cluster and a cluster parameter group. See [Creating an Amazon DocumentDB cluster](db-cluster-create.md) and [Creating Amazon DocumentDB cluster parameter groups](cluster_parameter_groups-create.md) for further instructions.

1. After creating your cluster parameter group, open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb). In the navigation pane, choose **Clusters** to add your new parameter group to a cluster.

1. Choose the cluster that you want to associate your parameter group with. Choose **Actions**, and then choose **Modify** to modify your cluster.

1. Under **Cluster options**, choose the new parameter group that you want to associate your cluster with.

1. Choose **Continue** to view a summary of your modifications.

1. After verifying your changes, you can apply them immediately or during the next maintenance window under **Scheduling of modifications**.

1. Choose **Modify cluster** to update your cluster with your new parameter group.

------
#### [ Using the AWS CLI ]

Before you begin, make sure that you have created an Amazon DocumentDB cluster and a cluster parameter group. You can [create an Amazon DocumentDB cluster](https://docs.aws.amazon.com//documentdb/latest/developerguide/db-cluster-create.html) using the AWS CLI `create-db-cluster` operation. You can [create a cluster parameter group](https://docs.aws.amazon.com//documentdb/latest/developerguide/cluster_parameter_groups-create.html) using the AWS CLI `create-db-cluster-parameter-group` operation.

To add your new cluster parameter group to your cluster, use the AWS CLI `modify-db-cluster` operation with the following parameters.
+ **--db-cluster-identifier** — The name of your cluster (for example, `sample-cluster`).
+ **--db-cluster-parameter-group-name** — The name of the parameter group that you want to associate your cluster with (for example, `sample-parameter-group`).

**Example**  

```
aws docdb modify-db-cluster \
    --db-cluster-identifier sample-cluster \
    --db-cluster-parameter-group-name sample-parameter-group
```
Output from this operation looks something like the following (JSON format).  

```
"DBCluster": {
    "AvailabilityZones": [
            "us-west-2c",
            "us-west-2b",
            "us-west-2a"
    ],
    "BackupRetentionPeriod": 1,
    "DBClusterIdentifier": "sample-cluster",
    "DBClusterParameterGroup": "sample-parameter-group",
    "DBSubnetGroup": "default",
   ...
}
```

------

# Copying Amazon DocumentDB cluster parameter groups
<a name="cluster_parameter_groups-copy"></a>

You can make a copy of a cluster parameter group in Amazon DocumentDB using the AWS Management Console or the AWS Command Line Interface (AWS CLI).

------
#### [ Using the AWS Management Console ]

The following procedure guides you through making a new cluster parameter group by making a copy of an existing cluster parameter group.

**To copy a cluster parameter group**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Parameter groups**.

1. In the **Cluster parameter groups** pane, choose the name of the cluster parameter group that you want to copy.

1. Choose **Actions**, and then choose **Copy** to copy that parameter group.

1. Under **Copy options**, enter a name and description for the new cluster parameter group. Then choose **Copy** to save your changes.

------
#### [ Using the AWS CLI ]

To make a copy of a cluster parameter group, use the `copy-db-cluster-parameter-group` operation with the following parameters.
+ **--source-db-cluster-parameter-group-identifier** — Required. The name or Amazon Resource Name (ARN) of the cluster parameter group that you want to make a copy of.

  If the source and target cluster parameter groups are in the same AWS Region, the identifier can be either a name or an ARN.

  If the source and target cluster parameter groups are in different AWS Regions, the identifier must be an ARN.
+ **--target-db-cluster-parameter-group-identifier** — Required. The name or ARN of the cluster parameter group copy.

  Constraints:
  + Cannot be null, empty, or blank.
  + Must contain 1–255 letters, numbers, or hyphens.
  + First character must be a letter.
  + Cannot end with a hyphen or contain two consecutive hyphens.
+ **--target-db-cluster-parameter-group-description** — Required. A user-supplied description for the cluster parameter group copy.

**Example**  
The following code makes a copy of `sample-parameter-group`, naming the copy `sample-parameter-group-copy`.  
For Linux, macOS, or Unix:  

```
aws docdb copy-db-cluster-parameter-group \
    --source-db-cluster-parameter-group-identifier sample-parameter-group \
    --target-db-cluster-parameter-group-identifier sample-parameter-group-copy \
    --target-db-cluster-parameter-group-description "Copy of sample-parameter-group"
```
For Windows:  

```
aws docdb copy-db-cluster-parameter-group ^
    --source-db-cluster-parameter-group-identifier sample-parameter-group ^
    --target-db-cluster-parameter-group-identifier sample-parameter-group-copy ^
    --target-db-cluster-parameter-group-description "Copy of sample-parameter-group"
```
Output from this operation looks something like the following (JSON format).  

```
{
    "DBClusterParameterGroup": {
        "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:cluster-pg:sample-parameter-group-copy",
        "DBClusterParameterGroupName": "sample-parameter-group-copy",
        "DBParameterGroupFamily": "docdb4.0",
        "Description": "Copy of sample-parameter-group"
    }
}
```

------

# Resetting Amazon DocumentDB cluster parameter groups
<a name="cluster_parameter_groups-reset"></a>

You can reset some or all of an Amazon DocumentDB cluster parameter group's parameter values to their default values by using the AWS Management Console or the AWS Command Line Interface (AWS CLI) to reset the cluster parameter group.

------
#### [ Using the AWS Management Console ]

Follow these steps to reset some or all of a cluster parameter group's parameter values to their default values.

**To reset a cluster parameter group's parameter values**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane on the left side of the console, choose **Parameter groups**.

1. In the **Cluster parameter groups** pane, choose the name of the cluster parameter group that you want to reset.

1. Choose **Actions**, and then choose **Reset** to reset that parameter group.

1. On the resulting **Cluster parameter group reset confirmation** page, confirm that you want to reset all cluster parameters for that parameter group to their defaults. Then choose **Reset** to reset your parameter group. You can also choose **Cancel** to discard your changes.

------
#### [ Using the AWS CLI ]

To reset some or all of a cluster parameter group's parameter values to their default values, use the `reset-db-cluster-parameter-group` operation with the following parameters.
+ **--db-cluster-parameter-group-name** — Required. The name of the cluster parameter group to reset.
+ **--parameters** — Optional. A list of `ParameterName` and `ApplyMethod` in the cluster parameter group to reset to their default values. Static parameters must be set to `pending-reboot` to take effect on the next instance restart or `reboot-db-instance` request. You must call `reboot-db-instance` for every instance in your cluster that you want the updated static parameter to apply to.

  This parameter and `--reset-all-parameters` are mutually exclusive: you can use either one but not both.
+ **--reset-all-parameters** or **--no-reset-all-parameters** — Optional. Specifies whether to reset all parameters (`--reset-all-parameters` or only some of the parameters (`--no-reset-all-parameters`) to their default values. The `--reset-all-parameters` parameter and `--parameters` are mutually exclusive: you can use either one but not both.

  When you reset the entire group, dynamic parameters are updated immediately. Static parameters are set to `pending-reboot` to take effect on the next instance restart or `reboot-db-instance` request. You must call `reboot-db-instance` for every instance in your cluster that you want the updated static parameter applied to.

**Example**  
**Example 1: Resetting all parameters to their default values**  
The following code resets all parameters in the cluster parameter group `sample-parameter-group` their default values.
For Linux, macOS, or Unix:  

```
aws docdb reset-db-cluster-parameter-group \
       --db-cluster-parameter-group-name sample-parameter-group \
       --reset-all-parameters
```
For Windows:  

```
aws docdb reset-db-cluster-parameter-group ^
       --db-cluster-parameter-group-name sample-parameter-group ^
       --reset-all-parameters
```
**Example 2: Resetting specified parameters to their default values**  
The following code resets the `tls` parameter in the cluster parameter group `sample-parameter-group` to its default value.
For Linux, macOS, or Unix:  

```
aws docdb reset-db-cluster-parameter-group \
       --db-cluster-parameter-group-name sample-parameter-group \
       --no-reset-all-parameters \
       --parameters ParameterName=tls,ApplyMethod=pending-reboot
```
For Windows:  

```
aws docdb reset-db-cluster-parameter-group ^
       --db-cluster-parameter-group-name sample-parameter-group ^
       --no-reset-all-parameters ^
       --parameters ParameterName=tls,ApplyMethod=pending-reboot
```
Output from this operation looks something like the following (JSON format).  

```
{
       "DBClusterParameterGroupName": "sample-parameter-group"
   }
```
**Rebooting a cluster instance**  
Before a static parameter's value is changed, the cluster instance must be rebooted. Reboot each instance in your cluster that you want the updated static parameter to apply to.
For Linux, macOS, or Unix:  

```
aws docdb reboot-db-instance \
       --db-instance-identifier sample-cluster-instance
```
For Windows:  

```
aws docdb reboot-db-instance ^
       --db-instance-identifier sample-cluster-instance
```

------

# Deleting Amazon DocumentDB cluster parameter groups
<a name="cluster_parameter_groups-delete"></a>

You can delete a custom Amazon DocumentDB cluster parameter group using the AWS Management Console or the AWS Command Line Interface (AWS CLI). You can't delete the `default.docdb4.0` cluster parameter group.

------
#### [ Using the AWS Management Console ]

**To delete a cluster parameter group**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Parameter groups**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the **Parameter groups** pane, choose the radio button to the left of the cluster parameter group that you want to delete.

1. Choose **Actions**, and then choose **Delete**.

1. In the **Delete** confirmation pane, choose **Delete** to delete the cluster parameter group. To keep the cluster parameter group, choose **Cancel**.

------
#### [ Using the AWS CLI ]

To delete a cluster parameter group, use the `delete-db-cluster-parameter-group` operation with the following parameter.
+ **--db-cluster-parameter-group-name** — Required. The name of the cluster parameter group to delete. This must be an existing cluster parameter group. *You cannot delete the `default.docdb4.0` cluster parameter group. *

**Example - Deleting a cluster parameter group**  
The following example walks you through the three steps for deleting a cluster parameter group:  

1. Finding the name of the cluster parameter group that you want to delete.

1. Deleting the specified cluster parameter group.

1. Verifying that the cluster parameter group was deleted.
**1. Find the name of the cluster parameter group that you want to delete.**  
The following code lists the names of all cluster parameter groups.
For Linux, macOS, or Unix:  

```
aws docdb describe-db-cluster-parameter-groups \
       --query 'DBClusterParameterGroups[*].[DBClusterParameterGroupName]'
```
For Windows:  

```
aws docdb describe-db-cluster-parameter-groups ^
       --query 'DBClusterParameterGroups[*].[DBClusterParameterGroupName]'
```
The output of the preceding operation is a list the names of cluster parameter groups similar to the following (JSON format).  

```
[
       [
           "default.docdb4.0"
       ],
       [
           "sample-parameter-group"
       ],
       [
           "sample-parameter-group-copy"
       ]
   ]
```
**2. Delete a specific cluster parameter group.**  
The following code deletes the cluster parameter group `sample-parameter-group-copy`.
For Linux, macOS, or Unix:  

```
aws docdb delete-db-cluster-parameter-group \
       --db-cluster-parameter-group-name sample-parameter-group-copy
```
For Windows:  

```
aws docdb delete-db-cluster-parameter-group ^
       --db-cluster-parameter-group-name sample-parameter-group-copy
```
There is no output from this operation.  
**3. Verify that the specified cluster parameter group was deleted.**  
The following code lists the names of all remaining cluster parameter groups.
For Linux, macOS, or Unix:  

```
aws docdb describe-db-cluster-parameter-groups \
       --query 'DBClusterParameterGroups[*].[DBClusterParameterGroupName]'
```
For Windows:  

```
aws docdb describe-db-cluster-parameter-groups ^
       --query 'DBClusterParameterGroups[*].[DBClusterParameterGroupName]'
```
The output of the preceding operation is a list of cluster parameter groups similar to the following (JSON format). The cluster parameter group that you just deleted should not be in the list.  
Output from this operation looks something like the following (JSON format).  

```
[
       [
           "default.docdb4.0"
       ],
       [
           "sample-parameter-group"
       ]
   ]
```

------

# Amazon DocumentDB cluster parameters reference
<a name="cluster_parameter_groups-list_of_parameters"></a>

When you change a dynamic parameter and save the cluster parameter group, the change is applied immediately regardless of the *Apply immediately* setting. When you change a static parameter and save the cluster parameter group, the parameter change takes effect after you manually reboot the instance. You can reboot an instance using the Amazon DocumentDB console or by explicitly calling `reboot-db-instance`.

The following table shows the parameters that apply to all instances in an Amazon DocumentDB cluster. 


**Amazon DocumentDB cluster-level parameters**  

| Parameter | Default Value | Valid Values | Modifiable | Apply Type | Data Type | Description | 
| --- | --- | --- | --- | --- | --- | --- | 
| audit\$1logs | disabled | enabled, disabled, ddl, dml\$1read, dml\$1write, all, none | Yes | Dynamic | String | Defines whether Amazon CloudWatch audit logs are enabled. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_groups-list_of_parameters.html) | 
| change\$1stream\$1log\$1retention\$1duration | 10800 | 3600-604800 | Yes | Dynamic | Integer | Defines the duration of time (in seconds) that the change stream log is retained and can be consumed.  | 
| default\$1collection\$1compression | disabled | enabled, disabled (Amazon DocumentDB 5.0) / zstd, lz4, none (Amazon DocumentDB8.0) | Yes | Dynamic | String | Defines the default compression setting for new collections in a cluster [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_groups-list_of_parameters.html) | 
| profiler | disabled | enabled, disabled | Yes | Dynamic | String | Enables profiling for slow operations. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_groups-list_of_parameters.html) | 
| profiler\$1sampling\$1rate | 1.0 | 0.0-1.0 | Yes | Dynamic | Float | Defines the sampling rate for logged operations. | 
| profiler\$1threshold\$1ms | 100 | 50-2147483646 | Yes | Dynamic | Integer | Defines the threshold for profiler. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_groups-list_of_parameters.html) | 
| planner\$1version | 3.0 | 1.0, 2.0, 3.0 | Yes | Dynamic | Float | Defines the query planner version to use for queries.[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_groups-list_of_parameters.html) | 
| tls | enabled | enabled, disabled, fips-140-3, tls1.2\$1, tls1.3\$1 | Yes | Static | String | Defines whether Transport Layer Security (TLS) connections are required. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_groups-list_of_parameters.html) | 
| ttl\$1monitor | enabled | enabled, disabled | Yes | Dynamic | String | Defines whether Time to Live (TTL) monitoring is enabled for the cluster. [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_groups-list_of_parameters.html) | 

# Modifying Amazon DocumentDB cluster parameters
<a name="cluster_parameter_groups-parameters"></a>

In Amazon DocumentDB, *cluster parameter groups* consist of *parameters* that apply to all of the instances that you create in the cluster. For custom cluster parameter groups, you can modify a parameter value at any time or reset all the parameter values to their defaults for parameter groups that you create. This section describes how to view the parameters that make up an Amazon DocumentDB cluster parameter group and their values, and how you can change or update these values.

Parameters can be *dynamic* or *static*. When you change a dynamic parameter and save the cluster parameter group, the change is applied immediately regardless of the `Apply Immediately` setting. When you change a static parameter and save the cluster parameter group, the parameter change takes effect only after you manually reboot the instances.

## Viewing an Amazon DocumentDB cluster parameter group's parameters
<a name="cluster_parameter_groups-describe_details_parameters"></a>

You can see an Amazon DocumentDB cluster's parameters and their values using the AWS Management Console or AWS CLI.

------
#### [ Using the AWS Management Console ]

**To view the details of a cluster parameter group**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Parameter groups**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the **Parameter groups** pane, choose the name of the cluster parameter group that you want to see the details of.

1. The resulting page shows the following values for each parameter: the parameter's name, current value, allowed values, whether the parameter is modifiable, apply type, data type, and description.  
![\[Screenshot: Parameter names and values.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-determine-parameter-value.png)

------
#### [ Using the AWS CLI ]

To see a cluster's parameter group's parameters and their values, use the `describe-db-cluster-parameters` operation with the following parameters.
+ **--db-cluster-parameter-group-name** — Required. The name of the cluster parameter group for which you want a detailed parameter list.
+ **--source** — Optional. If supplied, returns only parameters for a specific source. Parameter sources can be `engine-default`, `system`, or `user`.

**Example**  
The following code lists the parameters and their values for the `custom3-6-param-grp` parameter group. For more information about the parameter group, omit the `--query` line. For information about all parameter groups, omit the `--db-cluster-parameter-group-name` line.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-cluster-parameters \
   --db-cluster-parameter-group-name custom3-6-param-grp \
   --query 'Parameters[*].[ParameterName,ParameterValue]'
```
For Windows:  

```
aws docdb describe-db-cluster-parameters ^
   --db-cluster-parameter-group-name custom3-6-param-grp ^
   --query 'Parameters[*].[ParameterName,ParameterValue]'
```
Output from this operation looks something like the following (JSON format).  

```
[
    [
        "audit_logs",
        "disabled"
    ],
    [
        "tls",
        "enabled"
    ],
    [
        "ttl_monitor",
        "enabled"
    ]
]
```

------

## Modifying an Amazon DocumentDB cluster parameter group's parameters
<a name="cluster_parameter_groups-modify_parameters"></a>

You can modify a parameter group's parameters using the AWS Management Console or AWS CLI.

------
#### [ Using the AWS Management Console ]

**To update the parameters of a cluster parameter group**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Parameter groups**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the **Parameter groups** pane, choose the cluster parameter group that you want to update the parameters of.

1. The resulting page shows the parameters and their corresponding details for this cluster parameter group. Select a parameter to update.

1. On the top right of the page, choose **Edit** to change the value of the parameter. For more information about the types of cluster parameters, see [Amazon DocumentDB cluster parameters reference](cluster_parameter_groups-list_of_parameters.md).

1. Make your change, and then choose **Modify cluster parameter** to save the changes. To discard your changes, choose **Cancel**.

------
#### [ Using the AWS CLI ]

To modify a cluster parameter group's parameters, use the `modify-db-cluster-parameter-group` operation with the following parameters:
+ **--db-cluster-parameter-group-name** — Required. The name of the cluster parameter group that you are modifying.
+ **--parameters** — Required. The parameter or parameters that you are modifying. Each parameter entry must include the following:
  + **ParameterName** — The name of the parameter that you are modifying.
  + **ParameterValue** — The new value for this parameter.
  + **ApplyMethod** — How you want changes to this parameter applied. Permitted values are `immediate` and `pending-reboot`.
**Note**  
Parameters with the `ApplyType` of `static` must have an `ApplyMethod` of `pending-reboot`.

**To change the values of a cluster parameter group's parameters (AWS CLI)**

The following example changes the `tls` parameter.

1. **List the parameters and their values of `sample-parameter-group`**

   For Linux, macOS, or Unix:

   ```
   aws docdb describe-db-cluster-parameters \
       --db-cluster-parameter-group-name sample-parameter-group
   ```

   For Windows:

   ```
   aws docdb describe-db-cluster-parameters ^
       --db-cluster-parameter-group-name sample-parameter-group
   ```

   Output from this operation looks something like the following (JSON format).

   ```
   {
       "Parameters": [
           {
               "Source": "system",
               "ApplyType": "static",
               "AllowedValues": "disabled,enabled",
               "ParameterValue": "enabled",
               "ApplyMethod": "pending-reboot",
               "DataType": "string",
               "ParameterName": "tls",
               "IsModifiable": true,
               "Description": "Config to enable/disable TLS"
           },
           {
               "Source": "user",
               "ApplyType": "dynamic",
               "AllowedValues": "disabled,enabled",
               "ParameterValue": "enabled",
               "ApplyMethod": "pending-reboot",
               "DataType": "string",
               "ParameterName": "ttl_monitor",
               "IsModifiable": true,
               "Description": "Enables TTL Monitoring"
           }
       ]
   }
   ```

1. **Modify the `tls` parameter so that its value is `disabled`**. You can't modify the `ApplyMethod` because the `ApplyType` is `static`.

   For Linux, macOS, or Unix:

   ```
   aws docdb modify-db-cluster-parameter-group \
       --db-cluster-parameter-group-name sample-parameter-group \
       --parameters "ParameterName"=tls,ParameterValue=disabled,ApplyMethod=pending-reboot"
   ```

   For Windows:

   ```
   aws docdb modify-db-cluster-parameter-group ^
       --db-cluster-parameter-group-name sample-parameter-group ^
       --parameters "ParameterName=tls,ParameterValue=disabled,ApplyMethod=pending-reboot"
   ```

   Output from this operation looks something like the following (JSON format).

   ```
   {
       "DBClusterParameterGroupName": "sample-parameter-group"
   }
   ```

1. **Wait at least 5 minutes.**

1. **List the parameter values of `sample-parameter-group`.**

   For Linux, macOS, or Unix:

   ```
   aws docdb describe-db-cluster-parameters \
       --db-cluster-parameter-group-name sample-parameter-group
   ```

   For Windows:

   ```
   aws docdb describe-db-cluster-parameters ^
       --db-cluster-parameter-group-name sample-parameter-group
   ```

   Output from this operation looks something like the following (JSON format).

   ```
   {
       "Parameters": [
           {
               "ParameterName": "audit_logs",
               "ParameterValue": "disabled",
               "Description": "Enables auditing on cluster.",
               "Source": "system",
               "ApplyType": "dynamic",
               "DataType": "string",
               "AllowedValues": "enabled,disabled",
               "IsModifiable": true,
               "ApplyMethod": "pending-reboot"
           },
           {
               "ParameterName": "tls",
               "ParameterValue": "disabled",
               "Description": "Config to enable/disable TLS",
               "Source": "user",
               "ApplyType": "static",
               "DataType": "string",
               "AllowedValues": "disabled,enabled",
               "IsModifiable": true,
               "ApplyMethod": "pending-reboot"
           }
       ]
   }
   ```

------

# Understanding Amazon DocumentDB endpoints
<a name="endpoints"></a>

You can use Amazon DocumentDB (with MongoDB compatibility) endpoints to connect to a cluster or instance. Amazon DocumentDB has three different types of endpoints, each with its own purpose. 

**Topics**
+ [

# Finding a cluster's endpoints
](db-cluster-endpoints-find.md)
+ [

# Finding an instance's endpoint
](db-instance-endpoint-find.md)
+ [

# Connecting to endpoints
](endpoints-connecting.md)

**Cluster endpoint**  
A cluster endpoint is an endpoint for an Amazon DocumentDB cluster that connects to the current primary instance for the cluster. Each Amazon DocumentDB cluster has a single cluster endpoint and one primary instance. In case of a failover, the cluster endpoint is remapped to the new primary instance.

**Reader endpoint**  
A reader endpoint is an endpoint for an Amazon DocumentDB cluster that connects to one of the available replicas for that cluster. Each Amazon DocumentDB cluster has a reader endpoint. If there is more than one replica, the reader endpoint directs each connection request to one of the Amazon DocumentDB replicas.

**Instance endpoint**  
An instance endpoint is an endpoint that connects to a specific instance. Each instance in a cluster, regardless of whether it is a primary or replica instance, has its own unique instance endpoint. It is best to not use instance endpoints in your application. This is because they can change roles in case of a failover, thus requiring code changes in your application.

# Finding a cluster's endpoints
<a name="db-cluster-endpoints-find"></a>

You can find a cluster's cluster endpoint and reader endpoint using the Amazon DocumentDB console or AWS CLI.

------
#### [ Using the AWS Management Console ]

**To find a cluster's endpoints using the console:**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.

1. From the list of clusters, choose the name of the cluster you are interested in.

1. On the cluster details page, select the **Configuration** tab. In the **Configurations and status** section, you will find the **Cluster endpoint** and **Reader endpoint**.  
![\[Configurations and status section showing the cluster and reader endpoints.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cluster-endpoints.png)

1. To connect to this cluster, select the **Connectivity & security** tab. Locate the connection string for the `mongo` shell and the connection string that can be used in the application code to connect to your cluster.  
![\[Connect section showing a string to connect to the instance with the mongo shell and a string to connect to the cluster with an application.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/cluster-connection-strings.png)

------
#### [ Using the AWS CLI ]

To find the cluster and reader endpoints for your cluster using the AWS CLI, run the `describe-db-clusters` command with these parameters.

**Parameters**
+ **--db-cluster-identifier**—Optional. Specifies the cluster to return endpoints for. If omitted, returns endpoints for up to 100 of your clusters.
+ **--query**—Optional. Specifies the fields to display. Helpful by reducing the amount of data that you need to view to find the endpoints. If omitted, all information about a cluster is returned.
+ **--region**—Optional. Use the `--region` parameter to specify the Region that you want to apply the command to. If omitted, your default Region is used.

**Example**  
The following example returns the `DBClusterIdentifier`, endpoint (cluster endpoint), and `ReaderEndpoint` for `sample-cluster`.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-clusters \
   --region us-east-1 \
   --db-cluster-identifier sample-cluster \
   --query 'DBClusters[*].[DBClusterIdentifier,Port,Endpoint,ReaderEndpoint]'
```
For Windows:  

```
aws docdb describe-db-clusters ^
   --region us-east-1 ^
   --db-cluster-identifier sample-cluster ^
   --query 'DBClusters[*].[DBClusterIdentifier,Port,Endpoint,ReaderEndpoint]'
```
Output from this operation looks something like the following (JSON format).  

```
[
  [
     "sample-cluster",
     27017,
     "sample-cluster.cluster-corlsfccjozr.us-east-1.docdb.amazonaws.com",
     "sample-cluster.cluster-ro-corlsfccjozr.us-east-1.docdb.amazonaws.com"
  ]
]
```

Now that you have the cluster endpoint, you can connect to the cluster using either `mongo` or `mongodb`. For more information, see [Connecting to endpoints](endpoints-connecting.md).

------

# Finding an instance's endpoint
<a name="db-instance-endpoint-find"></a>

You can find the endpoint for an instance using the Amazon DocumentDB console or the AWS CLI.

------
#### [ Using the AWS Management Console ]

**To find an instance's endpoint using the console**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the Clusters navigation box, you’ll see the column **Cluster Identifier**. Your instances are listed under clusters, similar to the screenshot below.  
![\[Clusters table showing list of clusters under Cluster identifier column, with instances nested inside clusters.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/choose-clusters.png)

1. Check the box to the left of the instance you are interested in.

1. Scroll down to the **Details** section then locate the instance endpoint.  
![\[Console screenshot showing the details page with the instance endpoint highlighted.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-instance-endpoint.png)

1. To connect to this instance, scroll up to the **Connect** section. Locate the connection string for the `mongo` shell and a connection string that can be used in your application code to connect to your instance.  
![\[Console screenshot showing the Connect section with mongo shell and application connection strings highlighted.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/instance-connection-strings.png)

------
#### [ Using the AWS CLI ]

To find the instance endpoint using the AWS CLI, run the following command with these arguments.

**Arguments**
+ **--db-instance-identifier**—Optional. Specifies the instance to return the endpoint for. If omitted, returns the endpoint for up to 100 of your instances.
+ **--query**—Optional. Specifies the fields to display. Helpful by reducing the amount of data that you need to view to find the endpoints. If omitted, all information on an instance is returned. The `Endpoint` field has three members, so listing it in the query as in the following example returns all three members. If you're only interested in some of the `Endpoint` members, replace `Endpoint` in the query with the members you're interested in, as in the second example.
+ **--region**—Optional. Use the `--region` parameter to specify the Region that you want to apply the command to. If omitted, your default Region is used.

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-instances \
    --region us-east-1 \
    --db-instance-identifier sample-cluster-instance \
    --query 'DBInstances[*].[DBInstanceIdentifier,Endpoint]'
```
For Windows:  

```
aws docdb describe-db-instances ^
    --region us-east-1 ^
    --db-instance-identifier sample-cluster-instance ^
    --query 'DBInstances[*].[DBInstanceIdentifier,Endpoint]'
```
Output from this operation looks something like the following (JSON format).  

```
[
    [
        "sample-cluster-instance",
        {
            "Port": 27017,
            "Address": "sample-cluster-instance.corcjozrlsfc.us-east-1.docdb.amazonaws.com",
            "HostedZoneId": "Z2R2ITUGPM61AM"
        }
    ]
]
```
Reducing the output to eliminate the endpoint's `HostedZoneId`, you can modify your query by specifying `Endpoint.Port` and `Endpoint.Address`.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-instances \
    --region us-east-1 \
    --db-instance-identifier sample-cluster-instance \
    --query 'DBInstances[*].[DBInstanceIdentifier,Endpoint.Port,Endpoint.Address]'
```
For Windows:  

```
aws docdb describe-db-instances ^
    --region us-east-1 ^
    --db-instance-identifier sample-cluster-instance ^
    --query 'DBInstances[*].[DBInstanceIdentifier,Endpoint.Port,Endpoint.Address]'
```
Output from this operation looks something like the following (JSON format).  

```
[
    [
        "sample-cluster-instance",
        27017,
        "sample-cluster-instance.corcjozrlsfc.us-east-1.docdb.amazonaws.com"
    ]
]
```

Now that you have the instance endpoint, you can connect to the instance using either `mongo` or `mongodb`. For more information, see [Connecting to endpoints](endpoints-connecting.md).

------

# Connecting to endpoints
<a name="endpoints-connecting"></a>

When you have your endpoint, either cluster or instance, you can connect to it using the `mongo` shell or a connection string.

## Connecting using the mongo shell
<a name="endpoints-connecting-mongo"></a>

Use the following structure to construct the string that you need to connect to your cluster or instance using the `mongo` shell:

```
mongo \
    --ssl \
    --host Endpoint:Port \
    --sslCAFile global-bundle.pem \
    --username UserName \
    --password Password
```

**`mongo` shell examples**  
Connect to a cluster:

```
mongo \
    --ssl \
    --host sample-cluster.corcjozrlsfc.us-east-1.docdb.amazonaws.com:27017 \
    --sslCAFile global-bundle.pem \
    --username UserName \
    --password Password
```

Connect to an instance:

```
mongo \
    --ssl \
    --host sample-cluster-instance.corcjozrlsfc.us-east-1.docdb.amazonaws.com:27017 \
    --sslCAFile global-bundle.pem \
    --username UserName \
    --password Password
```

## Connecting using a connection string
<a name="endpoints-connecting-mongodb"></a>

Use the following structure to construct the connection string that you need to connect to your cluster or instance.

```
mongodb://UserName:Password@endpoint:port?replicaSet=rs0&ssl_ca_certs=global-bundle.pem 
```

**Connection string examples**  
Connect to a cluster:

```
mongodb://UserName:Password@sample-cluster.cluster-corlsfccjozr.us-east-1.docdb.amazonaws.com:27017?replicaSet=rs0&ssl_ca_certs=global-bundle.pem 
```

Connect to an instance:

```
mongodb://UserName:Password@sample-cluster-instance.cluster-corlsfccjozr.us-east-1.docdb.amazonaws.com:27017?replicaSet=rs0&ssl_ca_certs=global-bundle.pem 
```

 

# Understanding Amazon DocumentDB Amazon Resource Names (ARNs)
<a name="documentdb-arns"></a>

Resources that you create in AWS are each uniquely identified with an Amazon Resource Name (ARN). For certain Amazon DocumentDB (with MongoDB compatibility) operations, you must uniquely identify an Amazon DocumentDB resource by specifying its ARN. For example, when you add a tag to a resource, you must provide the resource's ARN. 

**Topics**
+ [Constructing an ARN](#documentdb-arns-constructing)
+ [Finding an ARN](#documentdb-arns-find)

## Constructing an ARN for an Amazon DocumentDB resource
<a name="documentdb-arns-constructing"></a>

You can construct an ARN for an Amazon DocumentDB resource using the following syntax. Amazon DocumentDB shares the format of Amazon Relational Database Service (Amazon RDS) ARNs. Amazon DocumentDB ARNs contain `rds` and not `docdb`.

`arn:aws:rds:region:account_number:resource_type:resource_id`


| Region Name | Region | Availability Zones (compute) | 
| --- | --- | --- | 
| US East (Ohio) | `us-east-2` | 3 | 
| US East (N. Virginia) | `us-east-1` | 6 | 
| US West (Oregon) | `us-west-2` | 4 | 
| Africa (Cape Town) | `af-south-1` | 3 | 
| South America (São Paulo) | `sa-east-1` | 3 | 
| Asia Pacific (Hong Kong) | `ap-east-1` | 3 | 
| Asia Pacific (Hyderabad) | `ap-south-2` | 3 | 
| Asia Pacific (Malaysia) | `ap-southeast-5` | 3 | 
| Asia Pacific (Mumbai) | `ap-south-1` | 3 | 
| Asia Pacific (Osaka) | `ap-northeast-3` | 3 | 
| Asia Pacific (Seoul) | `ap-northeast-2` | 4 | 
| Asia Pacific (Singapore) | `ap-southeast-1` | 3 | 
| Asia Pacific (Sydney) | `ap-southeast-2` | 3 | 
| Asia Pacific (Jakarta) | `ap-southeast-3` | 3 | 
| Asia Pacific (Melbourne) | `ap-southeast-4` | 3 | 
| Asia Pacific (Thailand) | `ap-southeast-7` | 3 | 
| Asia Pacific (Tokyo) | `ap-northeast-1` | 3 | 
| Canada (Central) | `ca-central-1` | 3 | 
| China (Beijing) Region | `cn-north-1` | 3 | 
| China (Ningxia) | `cn-northwest-1` | 3 | 
| Europe (Frankfurt) | `eu-central-1` | 3 | 
| Europe (Zurich) | `eu-central-2` | 3 | 
| Europe (Ireland) | `eu-west-1` | 3 | 
| Europe (London) | `eu-west-2` | 3 | 
| Europe (Milan) | `eu-south-1` | 3 | 
| Europe (Paris) | `eu-west-3` | 3 | 
| Europe (Spain) | `eu-south-2` | 3 | 
| Europe (Stockholm) | `eu-north-1` | 3 | 
| Mexico (Central) | `mx-central-1` | 3 | 
| Middle East (UAE) | `me-central-1` | 3 | 
| Israel (Tel Aviv) | `il-central-1` | 3 | 
| AWS GovCloud (US-West) | `us-gov-west-1` | 3 | 
| AWS GovCloud (US-East) | `us-gov-east-1` | 3 | 

**Note**  
The Amazon DocumentDB architecture separates storage and compute. For the storage layer, Amazon DocumentDB replicates six copies of your data across three AWS Availability Zones (AZs). The AZs listed in the table above are the number of AZs that you can use in a given region to provision compute instances. As an example, if you are launching an Amazon DocumentDB cluster in ap-northeast-1, your storage will be replicated six ways across three AZs but your compute instances will only be available in two AZs.

The following table shows the format that you should use when constructing an ARN for a particular Amazon DocumentDB resource. Amazon DocumentDB shares the format of Amazon RDS ARNs. Amazon DocumentDB ARNs contain `rds` and not `docdb`.


| Resource Type | ARN Format / Example | 
| --- | --- | 
|  Instance (`db`)  |  `arn:aws:rds:region:account_number:db:resource_id` <pre>arn:aws:rds:us-east-1:1234567890:db:sample-db-instance</pre>  | 
|  Cluster (`cluster`)  |  `arn:aws:rds:region:account_number:cluster:resource_id` <pre>arn:aws:rds:us-east-1:1234567890:cluster:sample-db-cluster</pre>  | 
|  Cluster parameter group (`cluster-pg`)  |  `arn:aws:rds:region:account_number:cluster-pg:resource_id` <pre>arn:aws:rds:us-east-1:1234567890:cluster-pg:sample-db-cluster-parameter-group</pre>  | 
|  Security group (`secgrp`)  |  `arn:aws:rds:region:account_number:secgrp:resource_id` <pre>arn:aws:rds:us-east-1:1234567890:secgrp:sample-public-secgrp</pre>  | 
|  Cluster snapshot (`cluster-snapshot`)  |  `arn:aws:rds:region:account_number:cluster-snapshot:resource_id` <pre>arn:aws:rds:us-east-1:1234567890:cluster-snapshot:sample-db-cluster-snapshot</pre>  | 
|  Subnet group (`subgrp`)  |  `arn:aws:rds:region:account_number:subgrp:resource_id` <pre>arn:aws:rds:us-east-1:1234567890:subgrp:sample-subnet-10</pre>  | 

## Finding an Amazon DocumentDB resource ARN
<a name="documentdb-arns-find"></a>

You can find the ARN of an Amazon DocumentDB resource using the AWS Management Console or the AWS CLI.

------
#### [ Using the AWS Management Console ]

To find an ARN using the console, navigate to the resource that you want an ARN for, and view the details for that resource. 

For example, you can get the ARN for a cluster by selecting the **Configuration** tab on the cluster details page. The ARN can be found in the **Configurations and status** section, as shown in the following screenshot.

![\[Console screenshot showing an ARN in the configurations and status section of the details pane.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/documentdb-arn.png)


------
#### [ Using the AWS CLI ]

To get an ARN using the AWS CLI for a particular Amazon DocumentDB resource, use the `describe` operation for that resource. The following table shows each AWS CLI operation and the ARN property that is used with the operation to get an ARN. 


| AWS CLI Command | ARN Property | 
| --- | --- | 
|  `describe-db-instances`  |  `DBInstanceArn`  | 
|  `describe-db-clusters`  |  `DBClusterArn`  | 
|  `describe-db-parameter-groups`  |  `DBParameterGroupArn`  | 
|  `describe-db-cluster-parameter-groups`  |  `DBClusterParameterGroupArn`  | 
|  `describe-db-security-groups`  |  `DBSecurityGroupArn`  | 
|  `describe-db-snapshots`  |  `DBSnapshotArn`  | 
|  `describe-db-cluster-snapshots`  |  `DBClusterSnapshotArn`  | 
|  `describe-db-subnet-groups`  |  `DBSubnetGroupArn`  | 

**Example - Finding the ARN for a cluster**  
The following AWS CLI operation finds the ARN for the cluster `sample-cluster`.  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-clusters \
    --db-cluster-identifier sample-cluster \
    --query 'DBClusters[*].DBClusterArn'
```
For Windows:  

```
aws docdb describe-db-clusters ^
    --db-cluster-identifier sample-cluster \
    --query 'DBClusters[*].DBClusterArn'
```
Output from this operation looks something like the following (JSON format).  

```
[
    "arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster"
]
```

**Example - Finding ARNs for multiple parameter groups**  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-cluster-parameter-groups \
   --query 'DBClusterParameterGroups[*].DBClusterParameterGroupArn'
```
For Windows:  

```
aws docdb describe-db-cluster-parameter-groups ^
   --query 'DBClusterParameterGroups[*].DBClusterParameterGroupArn'
```
Output from this operation looks something like the following (JSON format).  

```
[
    "arn:aws:rds:us-east-1:123456789012:cluster-pg:custom3-6-param-grp",
    "arn:aws:rds:us-east-1:123456789012:cluster-pg:default.aurora5.6",
    "arn:aws:rds:us-east-1:123456789012:cluster-pg:default.docdb3.6"
]
```

------

# Tagging Amazon DocumentDB resources
<a name="tagging"></a>

You can use Amazon DocumentDB (with MongoDB compatibility) tags to add metadata to your Amazon DocumentDB resources. These tags can be used with AWS Identity and Access Management (IAM) policies to manage access to Amazon DocumentDB resources and to control what actions can be applied to the resources. You can also use tags to track costs by grouping expenses for similarly tagged resources.

You can tag the following Amazon DocumentDB resources:
+ Clusters
+ Instances
+ Snapshots
+ Cluster snapshots
+ Parameter groups
+ Cluster parameter groups
+ Security groups
+ Subnet groups

## Overview of Amazon DocumentDB resource tags
<a name="tagging-overview"></a>

An Amazon DocumentDB tag is a name-value pair that you define and associate with an Amazon DocumentDB resource. The name is referred to as the *key*. Supplying a value for the key is optional. You can use tags to assign arbitrary information to an Amazon DocumentDB resource. You can use a tag key, for example, to define a category, and the tag value might be an item in that category. For example, you might define a tag key of `project` and a tag value of `Salix`, indicating that the Amazon DocumentDB resource is assigned to the Salix project. You can also use tags to designate Amazon DocumentDB resources as being used for test or production by using a key such as `environment=test` or `environment=production`. We recommend that you use a consistent set of tag keys to make it easier to track metadata that is associated with Amazon DocumentDB resources.

You can use tags to organize your AWS bill to reflect your own cost structure. To do this, sign up to get your AWS account bill with tag key values included. Then, to see the cost of combined resources, organize your billing information according to resources with the same tag key values. For example, you can tag several resources with a specific application name, and then organize your billing information to see the total cost of that application across several services. For more information, see [Using Cost Allocation Tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) in the *AWS Billing and Cost Management User Guide*. 

Each Amazon DocumentDB resource has a tag set, which contains all the tags that are assigned to that resource. A tag set can contain as many as 10 tags, or it can be empty. If you add a tag to an Amazon DocumentDB resource that has the same key as an existing tag on resource, the new value overwrites the old value.

AWS does not apply any semantic meaning to your tags; tags are interpreted strictly as character strings. Amazon DocumentDB can set tags on an instance or other Amazon DocumentDB resources, depending on the settings that you use when you create the resource. For example, Amazon DocumentDB might add a tag indicating that an instance is for production or for testing.

You can add a tag to a snapshot, but your bill will not reflect this grouping.

You can use the AWS Management Console or the AWS CLI to add, list, and delete tags on Amazon DocumentDB resources. When using the AWS CLI, you must provide the Amazon Resource Name (ARN) for the resource that you want to work with. For more information about Amazon DocumentDB ARNs, see [Understanding Amazon DocumentDB Amazon Resource Names (ARNs)](documentdb-arns.md).

## Tag constraints
<a name="tagging-constraints"></a>

The following constraints apply to Amazon DocumentDB tags:
+ Maximum number of tags per resource - 10
+ Maximum **Key** length - 128 Unicode characters
+ Maximum **Value** length - 256 Unicode characters
+ Valid characters for **Key** and **Value** - uppercase and lowercase letters in the UTF-8 character set, digits, space, and the following characters: `_ . : / = + -` and `@` (Java regex: `"^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$"`)
+ Tag keys and values are case sensitive.
+ The prefix `aws:` cannot be used for tag keys or values; it is reserved for AWS.

## Adding and updating tags on an Amazon DocumentDB resource
<a name="tagging-add"></a>

You can add up to 10 tags to a resource using the AWS Management Console or the AWS CLI.

------
#### [ Using the AWS Management Console ]

The process for adding a tag to a resource is similar regardless of what resource you're adding the tag to. In this example, you add a tag to a cluster.

**To add or update tags to a cluster using the console**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. From the navigation pane, choose **clusters**.

1. Choose the name of the cluster that you want to add tags to.

1. Scroll down to the **Tags** section, and then choose **Edit**.

1. For each tag you that want to add to this resource, do the following:

   1. To add a new tag, enter in the name of the tag in the **Key** box. To change a tag's value, find the tag's name in the **Key** column.

   1. To give the tag a new or updated value, enter a value for the tag in the **Value** box.

   1. If you have more tags to add, choose **Add**. Otherwise, when finished, choose **Save**.

------
#### [ Using the AWS CLI ]

The process for adding a tag to a resource is similar regardless of what resource you're adding the tags to. In this example, you add three tags to a cluster. The second tag, `key2`, has no value.

Use the AWS CLI operation `add-tags-to-resource` with these parameters.

**Parameters**
+ **--resource-name**—The ARN of the Amazon DocumentDB resource that you want to add tags to.
+ **--tags**—A list the tags (key-value pair) that you want to add to this resource in the format `Key=key-name,Value=tag-value`.

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb add-tags-to-resource \
    --resource-name arn:aws:rds:us-east-1:1234567890:cluster:sample-cluster \
    --tags Key=key1,Value=value1 Key=key2 Key=key3,Value=value3
```
For Windows:  

```
aws docdb add-tags-to-resource ^
    --resource-name arn:aws:rds:us-east-1:1234567890:cluster:sample-cluster \
    --tags Key=key1,Value=value1 Key=key2 Key=key3,Value=value3
```

The `add-tags-to-resource` operation produces no output. To see the results of the operation, use the `list-tags-for-resource` operation.

------

## Listing tags on an Amazon DocumentDB resource
<a name="tagging-list"></a>

You can use the AWS Management Console or the AWS CLI to get a listing of the tags for an Amazon DocumentDB resource.

------
#### [ Using the AWS Management Console ]

The process for listing tags on a resource is similar regardless of what resource you're adding the tag to. In this example, you list the tags for a cluster.

**To list the tags on a cluster using the console**

1. Open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. From the navigation pane, choose **clusters**.

1. Choose the name of the cluster that you want to list tags for.

1. To see a listing of the tags on this resource, scroll down to the **Tags** section.

------
#### [ Using the AWS CLI ]

The process for listing the tags on a resource is similar regardless of what resource you're listing the tag for. In this example, you list the tags on a cluster.

Use the AWS CLI operation `list-tags-for-resource` with these parameters.

**Parameters**
+ **--resource-name**—Required. The ARN of the Amazon DocumentDB resource that you want to list tags for.

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb list-tags-for-resource \
    --resource-name arn:aws:rds:us-east-1:1234567890:cluster:sample-cluster
```
For Windows:  

```
aws docdb list-tags-for-resource ^
    --resource-name arn:aws:rds:us-east-1:1234567890:cluster:sample-cluster
```

Output from this operation looks something like the following (JSON format).

```
{
    "TagList": [
        {
            "Key": "key1",
            "Value": "value1"
        },
        {
            "Key": "key2",
            "Value": ""
        },
        {
            "Key": "key3",
            "Value": "value3"
        }
    ]
}
```

------

## Removing tags from an Amazon DocumentDB resource
<a name="tagging-remove"></a>

You can use the AWS Management Console or the AWS CLI to remove tags from Amazon DocumentDB resources.

------
#### [ Using the AWS Management Console ]

The process for removing tags from a resource is similar regardless of what resource you're adding the tag to. In this example, you remove tags from a cluster.

**To remove tags from a cluster using the console**

1. Open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. From the navigation pane, choose **clusters**.

1. Choose the name of the cluster that you want to remove tags from.

1. Scroll down to the **Tags** section, and then choose **Edit**.

1. If you want to remove all tags from this resource, choose **Remove all**. Otherwise, for each tag that you want to remove from this resource, do the following:

   1. Locate the name of the tag in the **Key** column.

   1. Choose **Remove** on the same row as the tag key.

   1. When finished, choose **Save**.

------
#### [ Using the AWS CLI ]

The process for removing a tag from a resource is similar regardless of what resource you're removing the tag from. In this example, you remove a tag from a cluster.

Use the AWS CLI operation `remove-tags-from-resource` with these parameters.
+ **--resource-name**—Required. The ARN of the Amazon DocumentDB resource that you want to remove tags from.
+ **--tag-keys**—Required. A list the tag keys that you want removed from this resource.

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb remove-tags-from-resource \
    --resource-name arn:aws:rds:us-east-1:1234567890:cluster:sample-cluster \
    --tag-keys key1 key3
```
For Windows:  

```
aws docdb remove-tags-from-resource ^
    --resource-name arn:aws:rds:us-east-1:1234567890:cluster:sample-cluster \
    --tag-keys key1 key3
```

The `removed-tags-from-resource` operation produces no output. To see the results of the operation, use the `list-tags-for-resource` operation.

------

# Maintaining Amazon DocumentDB
<a name="db-instance-maintain"></a>

Periodically, Amazon DocumentDB performs maintenance on Amazon DocumentDB resources. Maintenance most often involves updates to the database engine (cluster maintenance) or the instance's underlying operating system (OS) (instance maintenance). Database engine updates are required patches and include security fixes, bug fixes, and enhancements to the database engine. While most operating system patches are optional, if you don't apply them for a while, the patch may be required and auto applied to maintain your security posture. So, we recommend that you apply operating system updates to your Amazon DocumentDB instances as soon as they are available. 

Database engine patches require that you take your Amazon DocumentDB clusters offline for a short time. Once available, these patches are automatically scheduled to apply during an upcoming scheduled maintenance window of your Amazon DocumentDB cluster.

Both cluster and instances maintenance have their own respective maintenance windows. Cluster and instance modifications that you have chosen not to apply immediately, are also applied during the maintenance window. By default, when you create a cluster, Amazon DocumentDB assigns a maintenance window for both a cluster and each individual instance. You can choose the maintenance window when creating a cluster or an instance. You can also modify the maintenance windows at any time to fit your business schedules or practices. It is generally advised to choose maintenance windows that minimize the impact of the maintenance on your application (for example, on evenings or weekends).

**Topics**
+ [

## Notifications for Amazon DocumentDB engine patches
](#patch-notifications)
+ [

## Viewing pending Amazon DocumentDB maintenance actions
](#view-pending-maintenance)
+ [

## Amazon DocumentDB engine updates
](#db-instance-updates-apply)
+ [

## User-initiated updates
](#user-initiated-updates)
+ [

## Managing your Amazon DocumentDB maintenance windows
](#maintenance-window)
+ [

## Amazon DocumentDB operating system updates
](#os-system-updates)
+ [

## Global clusters patching
](#global-clusters-patching)

## Notifications for Amazon DocumentDB engine patches
<a name="patch-notifications"></a>

You will receive maintenance notifications for required database engine patches through health events in the Health Dashboard (AHD) in the AWS console and through e-mails. When an Amazon DocumentDB engine maintenance patch becomes available in a particular AWS region, all impacted Amazon DocumentDB user accounts in the region will receive an AHD and email notification for each Amazon DocumentDB version affected by the patch. You can view these notifications under the **Scheduled changes** section of the AHD in the AWS console. The notification will have details about timing of patch availability, auto apply schedule, list of impacted clusters, and release notes. This notification will also be delivered via e-mail to the AWS account’s root user email address.

![\[Amazon DocumentDB console showing the Scheduled changes tab for engine patch upgrades.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/scheduled-changes.png)


Once you receive this notification, you can choose to self-apply these engine patches to your Amazon DocumentDB clusters before the scheduled auto-apply date. Or you can wait for the engine patches to get auto-applied during an upcoming maintenance window (default option).

**Note**  
The **Status** for the notification in the AHD will be set to 'Ongoing' until a new Amazon DocumentDB engine patch with a new engine patch version is released.  
Once the engine patch is applied to your Amazon DocumentDB cluster, the cluster's engine patch version will be updated to reflect the version in the notification. You can run the `db.runCommand({getEngineVersion: 1})` command to verify this update.

AWS Health also integrates with Amazon EventBridge which uses events to build scalable event-driven applications and integrates with over 20 targets, including AWS Lambda, Amazon Simple Queue Service (SQS), and others. You can use `AWS_DOCDB_DB_PATCH_UPGRADE_MAINTENANCE_SCHEDULED` event code to setup Amazon EventBridge before engine patches become available. You can setup EventBridge to respond to the event and auto-perform actions such as capturing event information, initiating additional events, sending notifications via additional channels such as push notifications to the AWS Console Mobile Application, and taking corrective or other actions, when an Amazon DocumentDB engine patch becomes available in your region. 

In the rare scenario of Amazon DocumentDB cancelling an engine patch, you will receive an AHD notification as well as an e-mail informing you about the cancellation. Accordingly, you can use the `AWS_DOCDB_DB_PATCH_UPGRADE_MAINTENANCE_CANCELLED` event code to setup Amazon EventBridge to respond to this event. View the *Amazon EventBridge User Guide* to learn more about using [Amazon EventBridge rules](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-rules.html).

## Viewing pending Amazon DocumentDB maintenance actions
<a name="view-pending-maintenance"></a>

You can view whether a maintenance update is available for your cluster by using the AWS Management Console or the AWS CLI.

If an update is available, you can do one of the following:
+ Defer a maintenance action that is currently scheduled for next maintenance window (for OS patches only).
+ Apply the maintenance actions immediately.
+ Schedule the maintenance actions to start during your next maintenance window.

**Note**  
If you take no action, required maintenance actions such as engine patches will be auto applied in an upcoming scheduled maintenance window.

The maintenance window determines when pending operations start, but it does not limit the total execution time of these operations.

------
#### [ Using the AWS Management Console ]

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.

1. If an update is available, it is indicated by the word **Available**, **Required**, or **Next Window** in the **Maintenance** column for the cluster on the Amazon DocumentDB console, as shown here:  
![\[Amazon DocumentDB console showing the Maintenance column for clusters.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/db-cluster-maintenance-updates-status.png)

1. To take an action, choose the cluster to show its details, then choose **Maintenance & backups**. The **Pending Maintenance** items appear.  
![\[Amazon DocumentDB console showing the cluster Maintenance window.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/cluster-maint-3.png)

------
#### [ Using the AWS CLI ]

Use the following AWS CLI operation to determine what maintenance actions are pending. The output here shows no pending maintenance actions.

```
aws docdb describe-pending-maintenance-actions
```

Output from this operation looks something like the following (JSON format).

```
{
    "PendingMaintenanceActions": []
}
```

------

## Amazon DocumentDB engine updates
<a name="db-instance-updates-apply"></a>

With Amazon DocumentDB, you can choose when to apply maintenance operations. You can decide when Amazon DocumentDB applies updates using the AWS Management Console or AWS CLI.

Use the procedures in this topic to immediately upgrade or schedule an upgrade for your cluster.

------
#### [ Using the AWS Management Console ]

You can use the console to manage updates for your Amazon DocumentDB clusters.

**To manage an update for a cluster**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**.

1. In the list of clusters, choose the button next to the name of the cluster that you want to apply the maintenance operation to.

1. On the **Actions** menu, choose one of the following:
   + **Upgrade now** to immediately perform the pending maintenance tasks.
   + **Upgrade at next window** to perform the pending maintenance tasks during the cluster's next maintenance window.

   Alternatively, you can click **Apply now** or **Apply at next maintenance window** in the Pending Maintenance section of the cluster **Maintenance & backups** tab (see **Using the AWS Management Console** in the previous section).
**Note**  
If there are no pending maintenance tasks, all of the preceding options are inactive.

------
#### [ Using the AWS CLI ]

To apply a pending update to a cluster, use the `apply-pending-maintenance-action` AWS CLI operation.

**Parameters**
+ **--resource-identifier**—The Amazon DocumentDB Amazon Resource Name (ARN) of the resource that the pending maintenance action applies to.
+ **--apply-action**—The pending maintenance action to apply to this resource.

  Valid values: `system-update` and `db-upgrade`.
+ **--opt-in-type**—A value that specifies the type of opt-in request, or undoes an opt-in request. An opt-in request of type `immediate` can't be undone.

  Valid values:
  + `immediate`—Apply the maintenance action immediately.
  + `next-maintenance`—Apply the maintenance action during the next maintenance window for the resource.
  + `undo-opt-in`—Cancel any existing `next-maintenance` opt-in requests.

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb apply-pending-maintenance-action \
    --resource-identifier arn:aws:rds:us-east-1:123456789012:db:docdb \
    --apply-action system-update \
    --opt-in-type immediate
```
For Windows:  

```
aws docdb apply-pending-maintenance-action ^
    --resource-identifier arn:aws:rds:us-east-1:123456789012:db:docdb ^
    --apply-action system-update ^
    --opt-in-type immediate
```

To return a list of resources that have at least one pending update, use the `describe-pending-maintenance-actions` AWS CLI command. 

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb describe-pending-maintenance-actions \
    --resource-identifier arn:aws:rds:us-east-1:001234567890:db:docdb
```
For Windows:  

```
aws docdb describe-pending-maintenance-actions ^
    --resource-identifier arn:aws:rds:us-east-1:001234567890:db:docdb
```
Output from this operation looks something like the following (JSON format).  

```
{
    "PendingMaintenanceActions": [
        {
            "ResourceIdentifier": "arn:aws:rds:us-east-1:001234567890:cluster:sample-cluster",
            "PendingMaintenanceActionDetails": [
                {
                    "Action": "system-update",
                    "CurrentApplyDate": "2019-01-11T03:01:00Z",
                    "Description": "db-version-upgrade",
                    "ForcedApplyDate": "2019-01-18T03:01:00Z",
                    "AutoAppliedAfterDate": "2019-01-11T03:01:00Z"
                }
            ]
        }
    ]
}
```

You can also return a list of resources for a cluster by specifying the `--filters` parameter of the`describe-pending-maintenance-actions` AWS CLI operation. The format for the `--filters` operation is `Name=filter-name,Values=resource-id,...`.

`db-cluster-id` is the acceptable values for the `Name` parameter of the filter. This value accepts a list of cluster identifiers or ARNs. The returned list only includes pending maintenance actions for the clusters identified by these identifiers or ARNs.

The following example returns the pending maintenance actions for the `sample-cluster1` and `sample-cluster2` clusters.

**Example**  
For Linux, macOS, or Unix:  

```
aws docdb describe-pending-maintenance-actions \
   --filters Name=db-cluster-id,Values=sample-cluster1,sample-cluster2
```
For Windows:  

```
aws docdb describe-pending-maintenance-actions ^
   --filters Name=db-cluster-id,Values=sample-cluster1,sample-cluster2
```

------

### Apply dates
<a name="db-instance-updates-apply-date"></a>

Each maintenance action has a respective apply date that you can find when describing the pending maintenance actions. When you read the output of pending maintenance actions from the AWS CLI, three dates are listed. These date values are `null` when the maintenance is optional. The values populate once the corresponding maintenance action is scheduled or applied.
+ **CurrentApplyDate**—The date the maintenance action will get applied either immediately or during the next maintenance window. 
+ **ForcedApplyDate**—The date when the maintenance will be automatically applied, independent of your maintenance window.
+ **AutoAppliedAfterDate**—The date after which the maintenance will be applied during the cluster's maintenance window.

## User-initiated updates
<a name="user-initiated-updates"></a>

As an Amazon DocumentDB user, you can initiate updates to your clusters or instances. For example, you can modify an instance's class to one with more or less memory, or you can change a cluster's parameter group. Amazon DocumentDB views these changes differently from Amazon DocumentDB initiated updates. For more information about modifying a cluster or instance, see the following:
+ [Modifying an Amazon DocumentDB cluster](db-cluster-modify.md)
+ [Modifying an Amazon DocumentDB instance](db-instance-modify.md)

To see a list of pending user initiated modifications, run the following command.

**Example**  
**To see pending user initiated changes for your instances**  
For Linux, macOS, or Unix:  

```
aws docdb describe-db-instances \
    --query 'DBInstances[*].[DBClusterIdentifier,DBInstanceIdentifier,PendingModifiedValues]'
```
For Windows:  

```
aws docdb describe-db-instances ^
    --query 'DBInstances[*].[DBClusterIdentifier,DBInstanceIdentifier,PendingModifiedValues]'
```
Output from this operation looks something like the following (JSON format).  
In this case, `sample-cluster-instance` has a pending change to a `db.r5.xlarge` instance class, while `sample-cluster-instance-2` has no pending changes.  

```
[
    [
        "sample-cluster",
        "sample-cluster-instance",
        {
            "DBInstanceClass": "db.r5.xlarge"
        }
    ],
    [
        "sample-cluster",
        "sample-cluster-instance-2",
        {}
    ]
]
```

## Managing your Amazon DocumentDB maintenance windows
<a name="maintenance-window"></a>

Each instance and cluster has a weekly maintenance window during which any pending changes are applied. The maintenance window is an opportunity to control when modifications and software patching occur, in the event either are requested or required. If a maintenance event is scheduled for a given week, it is initiated during the 30-minute maintenance window that you identify. Most maintenance events also complete during the 30-minute maintenance window, although larger maintenance events might take more than 30 minutes to complete.

The 30-minute maintenance window is selected at random from an 8-hour block of time per Region. If you don't specify a preferred maintenance window when you create the instance or cluster, Amazon DocumentDB assigns a 30-minute maintenance window on a randomly selected day of the week.

The following table lists the time blocks for each Region from which default maintenance windows are assigned.


| Region Name | Region | UTC Time Block | 
| --- | --- | --- | 
| US East (Ohio) | us-east-2 | 03:00-11:00 | 
| US East (N. Virginia) | us-east-1 | 03:00-11:00 | 
| US West (Oregon) | us-west-2 | 06:00-14:00 | 
| Africa (Cape Town) | af-south-1 | 03:00–11:00 | 
| Asia Pacific (Hong Kong) | ap-east-1 | 06:00-14:00 | 
| Asia Pacific (Hyderabad) | ap-south-2 | 06:30–14:30 | 
| Asia Pacific (Malaysia) | ap-southeast-5 | 13:00-21:00 | 
| Asia Pacific (Mumbai) | ap-south-1 | 06:00-14:00 | 
| Asia Pacific (Osaka) | ap-northeast-3 | 12:00-20:00 | 
| Asia Pacific (Seoul) | ap-northeast-2 | 13:00-21:00 | 
| Asia Pacific (Singapore) | ap-southeast-1 | 14:00-22:00 | 
| Asia Pacific (Sydney) | ap-southeast-2 | 12:00-20:00 | 
| Asia Pacific (Jakarta) | ap-southeast-3 | 08:00-16:00 | 
| Asia Pacific (Melbourne) | ap-southeast-4 | 11:00-19:00 | 
| Asia Pacific (Thailand) | ap-southeast-7 | 15:00-23:00 | 
| Asia Pacific (Tokyo) | ap-northeast-1 | 13:00-21:00 | 
| Canada (Central) | ca-central-1 | 03:00-11:00 | 
| China (Beijing) | cn-north-1 | 06:00-14:00 | 
| China (Ningxia) | cn-northwest-1 | 06:00-14:00 | 
| Europe (Frankfurt) | eu-central-1 | 21:00-05:00 | 
| Europe (Zurich) | eu-central-2 | 02:00-10:00 | 
| Europe (Ireland) | eu-west-1 | 22:00-06:00 | 
| Europe (London) | eu-west-2 | 22:00-06:00 | 
| Europe (Milan) | eu-south-1 | 02:00-10:00 | 
| Europe (Paris) | eu-west-3 | 23:59-07:29 | 
| Europe (Spain) | eu-south-2 | 02:00–10:00 | 
| Europe (Stockholm) | eu-north-1 | 04:00–12:00 | 
| Mexico (Central) | mx-central-1 | 03:00-11:00 | 
| Middle East (UAE) | me-central-1 | 05:00–13:00 | 
| South America (São Paulo) | sa-east-1 | 00:00-08:00 | 
| Israel (Tel Aviv) | il-central-1 | 04:00-12:00 | 
| AWS GovCloud (US-East) | us-gov-east-1 | 17:00-01:00 | 
| AWS GovCloud (US-West) | us-gov-west-1 | 06:00-14:00 | 

### Changing your Amazon DocumentDB maintenance windows
<a name="maintenance-windows"></a>

The maintenance window should fall at the time of lowest usage and thus might need changing from time to time. Your cluster or instance is unavailable during this time only if system changes (such as a scale storage operation or an instance class change) are being applied and require an outage. And then it is unavailable only for the minimum amount of time required to make the necessary changes.

For upgrades to the database engine, Amazon DocumentDB uses the cluster's preferred maintenance window and not the maintenance window for individual instances.

**To change the maintenance window**
+ For a cluster, see [Modifying an Amazon DocumentDB cluster](db-cluster-modify.md).
+ For an instance, see [Modifying an Amazon DocumentDB instance](db-instance-modify.md).

## Amazon DocumentDB operating system updates
<a name="os-system-updates"></a>

Instances in Amazon DocumentDB clusters occasionally require operating system updates. Amazon DocumentDB upgrades the operating system to a newer version to improve database performance and customers’ overall security posture. Operating system updates don't change the cluster engine version or instance class of an Amazon DocumentDB instance.

We recommend that you update the reader instances in a cluster first, then the writer instance to maximize the availability of your cluster. We don't recommend updating reader and writer instances at the same time, because you might incur longer downtime in the event of a failover.

Most operating system updates for Amazon DocumentDB are optional and don't have a set date to apply them. However, if you don't apply these updates for a while, they may eventually become required and automatically applied during your instance's maintenance window. This is to help maintain the security posture of your database. To avoid any unexpected downtime, we recommend that you apply operating system updates to your Amazon DocumentDB instances as soon as they become available and set your instance maintenance window at a time of your convenience as per your business needs. 

To be notified when a new optional update becomes available, you can subscribe to RDS-EVENT-0230 in the security patching event category. For information about subscribing to Amazon DocumentDB events, see [Subscribing to Amazon DocumentDB Event Subscriptions](https://docs.aws.amazon.com/documentdb/latest/developerguide/event-subscriptions.subscribe.html).

You should expect that when maintenance is performed on your cluster or instance, if the instance is a primary instance, it will fail over. To improve your availability, we recommend that you use more than one instance for your Amazon DocumentDB clusters. For more information, see [Amazon DocumentDB Failover](failover.md).

**Note**  
For certain management features, Amazon DocumentDB uses operational technology that is shared with Amazon Relational Database Service (Amazon RDS).

**Important**  
Your Amazon DocumentDB instance will be taken offline during the operating system upgrade. You can minimize cluster downtime by having a multi-instance cluster. If you do not have a multi-instance cluster then you can choose to temporarily create one by adding secondary instance(s) to perform this maintenance, then deleting the additional reader instance(s) once the maintenance is completed (regular charges for the secondary instance will apply). 

**Note**  
Staying current on all optional and mandatory updates might be required to meet various compliance obligations. We recommend that you apply all updates made available by Amazon DocumentDB routinely during your maintenance windows.

You can use the AWS Management Console or the AWS CLI to determine whether an update is available.

------
#### [ Using the AWS Management Console ]

To determine whether an update is available using the AWS Management Console:

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Clusters**, and then select the instance.

1. Choose **Maintenance**.

1. In the **Pending Maintenance** section, find the operating system update.

![\[Amazon DocumentDB console showing the Maintenance column for clusters.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/maintenance-available-1.png)


You can select the operating system update and click **Apply now** or **Apply at next maintenance window** in the **Pending Maintenance** section. If the maintenance value is **next window**, defer the maintenance items by choosing **Defer upgrade**. You can't defer a maintenance action if it has already started.

Alternatively, you can choose the instance from a list of clusters by clicking on **Clusters** in the navigation pane and select **Apply now** or **Apply at next maintenance window** from the **Actions** menu. 

------
#### [ Using the AWS CLI ]

To determine whether an update is available using the AWS CLI, call the `describe-pending-maintenance-actions` command:

```
aws docdb describe-pending-maintenance-actions
```

```
{
  "ResourceIdentifier": "arn:aws:docdb:us-east-1:123456789012:db:mydb2",
  "PendingMaintenanceActionDetails": [
    {
      "Action": "system-update",
      "Description": "New Operating System update is available"
    }
  ]
}
```

------

Operating system updates are specific to Amazon DocumentDB engine versions and instance classes. Therefore, Amazon DocumentDB instances receive or require updates at different times. When an operating system update is available for your instance based on its engine version and instance class, the update appears in the console. It can also be viewed by running the AWS CLI `describe-pending-maintenance-actions` command or by calling the `DescribePendingMaintenanceActions` API operation.

If you are not running the latest cluster patch release of your Amazon DocumentDB engine, you may not see operating system update listed as available maintenance. In order to view and manage the operating system update, you should first upgrade to the latest engine patch version.

## Global clusters patching
<a name="global-clusters-patching"></a>

Engine patch version of primary and secondary clusters are upgraded during each cluster's maintenance window. You will get a notification once a new engine patch version is available in all regions. The notification is sent out through Health Dashboard and email.

Once you receive the notification, you can choose to self-apply these engine patches to your secondary and primary clusters. Always patch secondary clusters first, then the primary cluster. This order ensures that FailOver and SwitchOver remain available throughout the patching process.

**Important**  
If you have already patched the primary cluster before the secondary clusters, update all secondary clusters to the same version as soon as possible. FailOver and SwitchOver will not work until all secondary and primary clusters are on the same version.

If you do not choose to self-apply, the patch will be applied automatically during each cluster's next maintenance window. It will be applied on secondary clusters first. Once all secondary clusters are patched, the patch will be applied on the primary cluster during the primary cluster's next maintenance window.

We recommend that you upgrade the primary and secondary DB clusters to the same version. You can only perform a managed cross-Region database failover on an Amazon DocumentDB global database if the primary and secondary DB clusters have the same engine version and patch level.

When primary and secondary clusters are on different engine patch versions, FailOver and SwitchOver requests will be rejected to avoid engine version compatibility issues. This can also occur when you add a new secondary cluster to a global database using a newer engine version than the primary cluster. To avoid this, ensure that any new secondary cluster is created with the same engine version as the primary cluster before adding it to the global database.

Once you receive the patch notification, we recommend upgrading your primary and secondary clusters to the latest version at your earliest opportunity to ensure SwitchOver and FailOver continue to work as expected. If your FailOver or SwitchOver request is rejected, check the engine patch version on your primary and secondary clusters. If they don't match, check and apply the available patch on your secondary and primary clusters.

# Understanding service-linked roles
<a name="service-linked-roles"></a>

Amazon DocumentDB (with MongoDB compatibility) uses AWS Identity and Access Management (IAM) service-linked roles. A [service-linked role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-service-linked-role) is a unique type of IAM role that is linked directly to Amazon DocumentDB. Service-linked roles are predefined by Amazon DocumentDB and include all the permissions that the service requires to call other AWS services on your behalf.

A service-linked role makes using Amazon DocumentDB easier because you don’t have to manually add the necessary permissions. Amazon DocumentDB defines the permissions of its service-linked roles, and unless defined otherwise, only Amazon DocumentDB can assume its roles. The defined permissions include the trust policy and the permissions policy, and that permissions policy cannot be attached to any other IAM entity.

You can delete the roles only after first deleting their related resources. This protects your Amazon DocumentDB resources because you can't inadvertently remove permission to access the resources.

For information about other services that support service-linked roles, see [AWS Services That Work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) and look for the services that have **Yes** in the **Service-Linked Role** column. Choose a **Yes** with a link to view the service-linked role documentation for that service.

## Amazon DocumentDB service-linked role permissions
<a name="service-linked-role-permissions"></a>

Amazon DocumentDB (with MongoDB compatibility) uses the service-linked role named **AWSServiceRoleForRDS** to allow Amazon DocumentDB to call AWS services on behalf of your clusters.

The AWSServiceRoleForRDS service-linked role trusts the following services to assume the role:
+ `docdb.amazonaws.com`

The role permissions policy allows Amazon DocumentDB to complete the following actions on the specified resources:
+ Actions on `ec2`:
  + `AssignPrivateIpAddresses`
  + `AuthorizeSecurityGroupIngress`
  + `CreateNetworkInterface`
  + `CreateSecurityGroup`
  + `DeleteNetworkInterface`
  + `DeleteSecurityGroup`
  + `DescribeAvailabilityZones`
  + `DescribeInternetGateways`
  + `DescribeSecurityGroups`
  + `DescribeSubnets`
  + `DescribeVpcAttribute`
  + `DescribeVpcs`
  + `ModifyNetworkInterfaceAttribute`
  + `RevokeSecurityGroupIngress`
  + `UnassignPrivateIpAddresses`
+ Actions on `sns`:
  + `ListTopic`
  + `Publish`
+ Actions on `cloudwatch`:
  + `PutMetricData`
  + `GetMetricData`
  + `CreateLogStream`
  + `PullLogEvents`
  + `DescribeLogStreams`
  + `CreateLogGroup`

**Note**  
You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. You might encounter the following error message:  
**Unable to create the resource. Verify that you have permission to create service linked role. Otherwise wait and try again later.**  
If you see this error, ensure that you have the following permissions enabled:  

```
{
    "Action": "iam:CreateServiceLinkedRole",
    "Effect": "Allow",
    "Resource": "arn:aws:iam::*:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS",
    "Condition": {
        "StringLike": {
            "iam:AWSServiceName":"rds.amazonaws.com"
        }
    }
}
```

For more information, see [Service-Linked Role Permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#service-linked-role-permissions) in the *IAM User Guide*.

## Creating an Amazon DocumentDB service-linked role
<a name="service-linked-roles-create"></a>

You don't need to manually create a service-linked role. When you create a cluster, Amazon DocumentDB creates the service-linked role for you. 

If you delete this service-linked role and then need to create it again, you can use the same process to re-create the role in your account. When you create a cluster, Amazon DocumentDB creates the service-linked role for you again. 

## Modifying an Amazon DocumentDB service-linked role
<a name="service-linked-roles-edit"></a>

Amazon DocumentDB does not allow you to modify the AWSServiceRoleForRDS service-linked role. After you create a service-linked role, you cannot change the name of the role because various entities might reference the role. However, you can modify the description of the role using IAM. For more information, see [Editing a Service-Linked Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#edit-service-linked-role) in the *IAM User Guide*.

## Deleting an Amazon DocumentDB service-linked role
<a name="service-linked-roles-delete"></a>

If you no longer need to use a feature or service that requires a service-linked role, we recommend that you delete that role. That way you don’t have an unused entity that is not actively monitored or maintained. However, you must delete all of your clusters before you can delete the service-linked role.

### Cleaning up an Amazon DocumentDB service-linked role
<a name="service-linked-roles-clean-up"></a>

Before you can use IAM to delete a service-linked role, you must first confirm that the role has no active sessions and remove any resources used by the role.

**To check whether the service-linked role has an active session using the console**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane of the IAM console, choose **Roles**, and then choose the name (not the check box) of the **AWSServiceRoleForRDS** role.

1. On the **Summary** page for the selected role, choose the **Access Advisor** tab.

1. On the **Access Advisor** tab, review the recent activity for the service-linked role.
**Note**  
If you are unsure whether Amazon DocumentDB is using the AWSServiceRoleForRDS role, you can try to delete the role. If the service is using the role, then the deletion fails and you can view the Regions where the role is being used. If the role is being used, then you must wait for the session to end before you can delete the role. You cannot revoke the session for a service-linked role. 

If you want to remove the AWSServiceRoleForRDS role, you must first delete *all* your instances and clusters. For information about deleting instances and clusters, see the following topics:
+ [Deleting an Amazon DocumentDB instance](db-instance-delete.md)
+ [Deleting an Amazon DocumentDB cluster](db-cluster-delete.md)

## Supported regions for Amazon DocumentDB service-linked roles
<a name="slr-regions"></a>

Amazon DocumentDB supports using service-linked roles in all of the Regions where the service is available. For more information, see [https://docs.aws.amazon.com/documentdb/latest/developerguide/regions-and-azs.html#regions-and-azs-availability](https://docs.aws.amazon.com/documentdb/latest/developerguide/regions-and-azs.html#regions-and-azs-availability).

 

# Using change streams with Amazon DocumentDB
<a name="change_streams"></a>

The change streams feature in Amazon DocumentDB (with MongoDB compatibility) provides a time-ordered sequence of change events that occur within your cluster’s collections. You can read events from a change stream to implement many different use cases, including the following:
+ Change notification
+ Full-text search with Amazon OpenSearch Service (OpenSearch Service)
+ Analytics with Amazon Redshift

Applications can use change streams to subscribe to data changes on individual collections. Change streams events are ordered as they occur on the cluster and are stored for 3 hours (by default) after the event has been recorded. The retention period can be extended up to 7 days using the `change_stream_log_retention_duration` parameter. To modify the change stream retention period, please see [Modifying the Change Stream Log Retention Duration ](https://docs.aws.amazon.com/documentdb/latest/developerguide/change_streams.html#change_streams-modifying_log_retention).

**Topics**
+ [

## Supported operations
](#change_streams-supported_ops)
+ [

## Billing
](#change_streams-billing)
+ [

## Limitations
](#change_streams-limitations)
+ [

## Enabling change streams
](#change_streams-enabling)
+ [

## Example: using change streams with Python
](#change_streams-using_example)
+ [

## Full document lookup
](#change_streams-lookup)
+ [

## Resuming a change stream
](#change_streams-resuming)
+ [

## Resuming a change stream with `startAtOperationTime`
](#change_streams-startAtOperation)
+ [

## Resuming a change stream with `postBatchResumeToken`
](#change_streams-postBatchResumeToken)
+ [

## Transactions in change streams
](#change_streams-transactions)
+ [

## Modifying the change stream log retention duration
](#change_streams-modifying_log_retention)
+ [

## Using change streams on secondary instances
](#change-streams-secondary-instances)

## Supported operations
<a name="change_streams-supported_ops"></a>

Amazon DocumentDB supports the following operations for change streams:
+ All change events supported in the MongoDB `db.collection.watch()`, `db.watch()` and `client.watch()` API.
+ Full document lookup for updates.
+ Aggregation stages: `$match`, `$project`, `$redact`, and `$addFields`and `$replaceRoot`.
+ Resuming a change stream from a resume token
+ Resuming a change stream from a timestamp using `startAtOperation` (applicable to Amazon DocumentDB 4.0\$1)

## Billing
<a name="change_streams-billing"></a>

The Amazon DocumentDB change streams feature is disabled by default and does not incur any additional charges until the feature is enabled. Using change streams in a cluster incurs additional read and write IOs and storage costs. You can use the `modifyChangeStreams` API operation to enable this feature for your cluster. For more information on pricing, see [Amazon DocumentDB pricing](https://aws.amazon.com/documentdb/pricing/). 

## Limitations
<a name="change_streams-limitations"></a>

Change streams have the following limitations in Amazon DocumentDB:
+ On Amazon DocumentDB 3.6. and Amazon DocumentDB 4.0, change streams can only be opened from a connection to the primary instance of an Amazon DocumentDB cluster. Reading from change streams on a replica instance is not supported on Amazon DocumentDB 3.6. and Amazon DocumentDB 4.0. When invoking the `watch()` API operation, you must specify a `primary` read preference to ensure that all reads are directed to the primary instance (see the [Example](#change_streams-using_example) section). 
+ On Amazon DocumentDB 5.0, change streams can be opened from both primary instance and secondary instances, including global clusters. You can specify a secondary read preference to redirect the change streams to secondary instances. See [Using change streams on secondary instances](#change-streams-secondary-instances) for additional best practices and limitations.
+ Events written to a change stream for a collection are available for up to 7 days (the default is 3 hours). Change streams data is deleted after the log retention duration window, even if no new changes have occurred. 
+ A long-running write operation on a collection like `updateMany` or `deleteMany` can temporarily stall the writing of change streams events until the long running write operation is complete.
+ Amazon DocumentDB does not support the MongoDB operations log (`oplog`).
+ With Amazon DocumentDB, you must explicitly enable change streams on a given collection.
+ If the total size of a change streams event (including the change data and full document, if requested) is greater than `16 MB`, the client will experience a read failure on the change streams.
+ The Ruby driver is currently not supported when using `db.watch()` and `client.watch()` with Amazon DocumentDB 3.6.
+ The output from the `updateDescription` command in change streams is different in Amazon DocumentDB than in MongoDB when the updated value of the field is the same as the previous one:
  + Amazon DocumentDB doesn't return a field in the `updateDescription` output if the provided field is specified in the `$set` command and its target value is already equal to the source value.
  + MongoDB returns the field in the output, even if the specified value is equal to the current value.

## Enabling change streams
<a name="change_streams-enabling"></a>

You can enable Amazon DocumentDB change streams for all collections within a given database, or only for selected collections. The following are examples of how to enable change streams for different use cases using the mongo shell. Empty strings are treated as wildcards when specifying database and collection names.

```
//Enable change streams for the collection "foo" in database "bar"
db.adminCommand({modifyChangeStreams: 1,
    database: "bar",
    collection: "foo", 
    enable: true});
```

```
//Disable change streams on collection "foo" in database "bar"
db.adminCommand({modifyChangeStreams: 1,
    database: "bar",
    collection: "foo", 
    enable: false});
```

```
//Enable change streams for all collections in database "bar"
db.adminCommand({modifyChangeStreams: 1,
    database: "bar",
    collection: "", 
    enable: true});
```

```
//Enable change streams for all collections in all databases in a cluster
db.adminCommand({modifyChangeStreams: 1,
    database: "",
    collection: "", 
    enable: true});
```

Change streams will be enabled for a collection if any of the following are true:
+ Both the database and collection are explicitly enabled.
+ The database containing the collection is enabled. 
+ All databases are enabled.

Dropping a collection from a database does not disable change streams for that collection if the parent database also has change streams enabled, or if all databases in the cluster are enabled. If a new collection is created with the same name as the deleted collection, change streams will be enabled for that collection.

You can list all of your cluster’s enabled change streams by using the `$listChangeStreams` aggregation pipeline stage. All aggregation stages supported by Amazon DocumentDB can be used in the pipeline for additional processing. If a previously enabled collection has been disabled, it will not appear in the `$listChangeStreams` output.

```
//List all databases and collections with change streams enabled
cursor = new DBCommandCursor(db,
    db.runCommand(
        {aggregate: 1,
        pipeline: [{$listChangeStreams: 1}], 
        cursor:{}}));
```

```
//List of all databases and collections with change streams enabled 
{ "database" : "test", "collection" : "foo" } 
{ "database" : "bar", "collection" : "" }
{ "database" : "", "collection" : "" }
```

```
//Determine if the database “bar” or collection “bar.foo” have change streams enabled
cursor = new DBCommandCursor(db,
  db.runCommand(
      {aggregate: 1,
       pipeline: [{$listChangeStreams: 1},
                  {$match: {$or: [{database: "bar", collection: "foo"},
                                  {database: "bar", collection: ""},
                                  {database: "", collection: ""}]}}
                 ],
      cursor:{}}));
```

## Example: using change streams with Python
<a name="change_streams-using_example"></a>

The following is an example of using an Amazon DocumentDB change stream with Python at the collection level.

```
import os
import sys
from pymongo import MongoClient, ReadPreference
      
username = "DocumentDBusername"
password = <Insert your password> 

clusterendpoint = "DocumentDBClusterEndpoint”
client = MongoClient(clusterendpoint, username=username, password=password, tls='true', tlsCAFile='global-bundle.pem')

db = client['bar']
 
#While ‘Primary’ is the default read preference, here we give an example of
#how to specify the required read preference when reading the change streams
coll = db.get_collection('foo', read_preference=ReadPreference.PRIMARY)
#Create a stream object
stream = coll.watch()
#Write a new document to the collection to generate a change event
coll.insert_one({'x': 1})
#Read the next change event from the stream (if any)
print(stream.try_next())

"""
Expected Output:
{'_id': {'_data': '015daf94f600000002010000000200009025'},
'clusterTime': Timestamp(1571788022, 2),
'documentKey': {'_id': ObjectId('5daf94f6ea258751778163d6')},
'fullDocument': {'_id': ObjectId('5daf94f6ea258751778163d6'), 'x': 1},
'ns': {'coll': 'foo', 'db': 'bar'},
'operationType': 'insert'}
"""

#A subsequent attempt to read the next change event returns nothing, as there are no new changes
print(stream.try_next())

"""
Expected Output:
None
""" 
 
#Generate a new change event by updating a document
result = coll.update_one({'x': 1}, {'$set': {'x': 2}})
print(stream.try_next())

"""
Expected Output:
{'_id': {'_data': '015daf99d400000001010000000100009025'},
'clusterTime': Timestamp(1571789268, 1),
'documentKey': {'_id': ObjectId('5daf9502ea258751778163d7')},
'ns': {'coll': 'foo', 'db': 'bar'},
'operationType': 'update',
'updateDescription': {'removedFields': [], 'updatedFields': {'x': 2}}}
"""
```

The following is an example of using an Amazon DocumentDB change stream with Python at the database level. 

```
import os
import sys
from pymongo import MongoClient

username = "DocumentDBusername"
password = <Insert your password>
clusterendpoint = "DocumentDBClusterEndpoint”
client = MongoClient(clusterendpoint, username=username, password=password, tls='true', tlsCAFile='global-bundle.pem')

db = client['bar']
#Create a stream object
stream = db.watch()
coll = db.get_collection('foo')
#Write a new document to the collection foo to generate a change event
coll.insert_one({'x': 1})
 
#Read the next change event from the stream (if any)
print(stream.try_next())

"""
Expected Output:
{'_id': {'_data': '015daf94f600000002010000000200009025'},
'clusterTime': Timestamp(1571788022, 2),
'documentKey': {'_id': ObjectId('5daf94f6ea258751778163d6')},
'fullDocument': {'_id': ObjectId('5daf94f6ea258751778163d6'), 'x': 1},
'ns': {'coll': 'foo', 'db': 'bar'},
'operationType': 'insert'}
"""
#A subsequent attempt to read the next change event returns nothing, as there are no new changes
print(stream.try_next())

"""
Expected Output:
None
""" 
 
coll = db.get_collection('foo1')

#Write a new document to another collection to generate a change event
coll.insert_one({'x': 1})
print(stream.try_next())

"""
Expected Output: Since the change stream cursor was the database level you can see change events from different collections in the same database
{'_id': {'_data': '015daf94f600000002010000000200009025'},
'clusterTime': Timestamp(1571788022, 2),
'documentKey': {'_id': ObjectId('5daf94f6ea258751778163d6')},
'fullDocument': {'_id': ObjectId('5daf94f6ea258751778163d6'), 'x': 1},
'ns': {'coll': 'foo1', 'db': 'bar'},
'operationType': 'insert'}
"""
```

## Full document lookup
<a name="change_streams-lookup"></a>

The update change event does not include the full document; it includes only the change that was made. If your use case requires the complete document affected by an update, you can enable full document lookup when opening the stream. 

The `fullDocument` document for an update change streams event represents the most current version of the updated document at the time of document lookup. If changes occurred between the update operation and the `fullDocument` lookup, the `fullDocument` document might not represent the document state at update time.

To create a stream object with update lookup enabled, use this example:

```
stream = coll.watch(full_document='updateLookup')
 
#Generate a new change event by updating a document
result = coll.update_one({'x': 2}, {'$set': {'x': 3}})

stream.try_next()
```

The output of the stream object will look something like this:

```
{'_id': {'_data': '015daf9b7c00000001010000000100009025'},
'clusterTime': Timestamp(1571789692, 1),
'documentKey': {'_id': ObjectId('5daf9502ea258751778163d7')},
'fullDocument': {'_id': ObjectId('5daf9502ea258751778163d7'), 'x': 3},
'ns': {'coll': 'foo', 'db': 'bar'},
'operationType': 'update',
'updateDescription': {'removedFields': [], 'updatedFields': {'x': 3}}}
```

## Resuming a change stream
<a name="change_streams-resuming"></a>

You can resume a change stream later by using a resume token, which is equal to the `_id` field of the last retrieved change event document.

```
import os
import sys
from pymongo import MongoClient

username = "DocumentDBusername"
password = <Insert your password> 
clusterendpoint = "DocumentDBClusterEndpoint”
client = MongoClient(clusterendpoint, username=username, password=password, tls='true', tlsCAFile='global-bundle.pem', retryWrites='false')

db = client['bar']
coll = db.get_collection('foo')
#Create a stream object
stream = db.watch()
coll.update_one({'x': 1}, {'$set': {'x': 4}})
event = stream.try_next()
token = event['_id']
print(token)

"""
Output: This is the resume token that we will later us to resume the change stream
{'_data': '015daf9c5b00000001010000000100009025'}
"""
#Python provides a nice shortcut for getting a stream’s resume token
print(stream.resume_token)

"""
Output
{'_data': '015daf9c5b00000001010000000100009025'}
"""
#Generate a new change event by updating a document
result = coll.update_one({'x': 4}, {'$set': {'x': 5}})
#Generate another change event by inserting a document
result = coll.insert_one({'y': 5})
#Open a stream starting after the selected resume token
stream = db.watch(full_document='updateLookup', resume_after=token)
#Our first change event is the update with the specified _id
print(stream.try_next())

"""
#Output: Since we are resuming the change stream from the resume token, we will see all events after the first update operation. In our case, the change stream will resume from the update operation {x:5}

{'_id': {'_data': '015f7e8f0c000000060100000006000fe038'}, 
'operationType': 'update', 
'clusterTime': Timestamp(1602129676, 6), 
'ns': {'db': 'bar', 'coll': 'foo'}, 
'documentKey': {'_id': ObjectId('5f7e8f0ac423bafbfd9adba2')}, 
'fullDocument': {'_id': ObjectId('5f7e8f0ac423bafbfd9adba2'), 'x': 5}, 
'updateDescription': {'updatedFields': {'x': 5}, 'removedFields': []}}
"""
#Followed by the insert
print(stream.try_next())

"""
#Output:
{'_id': {'_data': '015f7e8f0c000000070100000007000fe038'}, 
'operationType': 'insert', 
'clusterTime': Timestamp(1602129676, 7), 
'ns': {'db': 'bar', 'coll': 'foo'}, 
'documentKey': {'_id': ObjectId('5f7e8f0cbf8c233ed577eb94')}, 
'fullDocument': {'_id': ObjectId('5f7e8f0cbf8c233ed577eb94'), 'y': 5}}
"""
```

## Resuming a change stream with `startAtOperationTime`
<a name="change_streams-startAtOperation"></a>

You can resume a change stream later from a particular time stamp by using `startAtOperationTime`.

**Note**  
The ability to use `startAtOperationTime` is available in Amazon DocumentDB 4.0\$1. When using `startAtOperationTime`, the change stream cursor will only return changes that occurred at or after the specified Timestamp. The `startAtOperationTime` and `resumeAfter` commands are mutually exclusive and thus cannot be used together.

```
import os
import sys
from pymongo import MongoClient

username = "DocumentDBusername"
password = <Insert your password> 
clusterendpoint = "DocumentDBClusterEndpoint”
client = MongoClient(clusterendpoint, username=username, password=password, tls='true', tlsCAFile='rds-root-ca-2020.pem',retryWrites='false')
db = client['bar']
coll = db.get_collection('foo')
#Create a stream object
stream = db.watch()
coll.update_one({'x': 1}, {'$set': {'x': 4}})
event = stream.try_next()
timestamp = event['clusterTime']
print(timestamp)
"""
Output
Timestamp(1602129114, 4)
"""
#Generate a new change event by updating a document
result = coll.update_one({'x': 4}, {'$set': {'x': 5}})
result = coll.insert_one({'y': 5})
#Generate another change event by inserting a document
#Open a stream starting after specified time stamp

stream = db.watch(start_at_operation_time=timestamp)
print(stream.try_next())

"""
#Output: Since we are resuming the change stream at the time stamp of our first update operation (x:4), the change stream cursor will point to that event
{'_id': {'_data': '015f7e941a000000030100000003000fe038'}, 
'operationType': 'update', 
'clusterTime': Timestamp(1602130970, 3), 
'ns': {'db': 'bar', 'coll': 'foo'}, 
'documentKey': {'_id': ObjectId('5f7e9417c423bafbfd9adbb1')}, 
'updateDescription': {'updatedFields': {'x': 4}, 'removedFields': []}}
"""

print(stream.try_next())
"""
#Output: The second event will be the subsequent update operation (x:5)
{'_id': {'_data': '015f7e9502000000050100000005000fe038'}, 
'operationType': 'update', 
'clusterTime': Timestamp(1602131202, 5),
'ns': {'db': 'bar', 'coll': 'foo'}, 
'documentKey': {'_id': ObjectId('5f7e94ffc423bafbfd9adbb2')}, 
'updateDescription': {'updatedFields': {'x': 5}, 'removedFields': []}}
"""

print(stream.try_next())

"""
#Output: And finally the last event will be the insert operation (y:5)
{'_id': {'_data': '015f7e9502000000060100000006000fe038'}, 
'operationType': 'insert', 
'clusterTime': Timestamp(1602131202, 6), 
'ns': {'db': 'bar', 'coll': 'foo'}, 
'documentKey': {'_id': ObjectId('5f7e95025c4a569e0f6dde92')}, 
'fullDocument': {'_id': ObjectId('5f7e95025c4a569e0f6dde92'), 'y': 5}}
"""
```

## Resuming a change stream with `postBatchResumeToken`
<a name="change_streams-postBatchResumeToken"></a>

Amazon DocumentDB change stream now returns an additional field called `postBatchResumeToken`. This field is returned from the `$changestream` command and `getMore` command.

Example of the `$changestream` command in Python:

```
db.command({"aggregate": "sales", "pipeline": [{ "$changeStream": {}}], "cursor": {"batchSize": 1}})
```

Expected output:

```
cursor" : {
   "firstBatch" : [ ],
   "postBatchResumeToken" : {"_data" : "0167c8cbe60000000004"},
   "id" : NumberLong("9660788144470"),
   "ns" : "test.sales"
}
```

Example of the `getMore` command in Python:

```
db.command({"getMore": NumberLong(<cursor id>), "collection": "sales", "batchSize": 1 })
```

Expected output

```
cursor" : {
   "nextBatch" : [ ],
   "postBatchResumeToken" : {"_data" : "0167c8cbe60000000004"},
   "id" : NumberLong("9660788144470"),
   "ns" : "test.sales"
}
```

The `postBatchResumeToken` field can be used to open new change stream cursors in the `resumeAfter` field, similar to how the resume token is used.

Open a stream starting after the selected `postBatchResumeToken`:

```
post_batch_resume_token = output['cursor']['postBatchResumeToken']
stream = db.watch(full_document='updateLookup', resume_after=post_batch_resume_token)
```

Unlike a regular resume token that always corresponds to an operations log (oplog) entry that reflects an actual event, `postBatchResumeToken` corresponds to an oplog entry the change stream has scanned up to on the server, which is not necessarily a matching change.

Attempting to resume with an old regular resume token will force the database to scan all the oplog entries between the specified time stamp and the current time. This may generate a lot of queries internally with each sub-query scanning for a small period of time. This will cause a spike in CPU usage and degrade the database performance. Resuming with the last `postBatchResumeToken` skips the scanning of unmatched oplog entries.

## Transactions in change streams
<a name="change_streams-transactions"></a>

Change stream events will not contain events from uncommitted and/or aborted transactions. For example, if you start a transaction with one `INSERT` operation and one `UPDATE` operation, and if your `INSERT` operation succeeds, but the `UPDATE` operation fails, the transaction will be rolled back. Since this transaction was rolled back, your change stream will not contain any events for this transaction.

## Modifying the change stream log retention duration
<a name="change_streams-modifying_log_retention"></a>

You can modify the change stream log retention duration to be between 1 hour and 7 days using the AWS Management Console or the AWS CLI.

------
#### [ Using the AWS Management Console ]

**To modify the change stream log retention duration**

1. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb).

1. In the navigation pane, choose **Parameter groups **.
**Tip**  
If you don't see the navigation pane on the left side of your screen, choose the menu icon (![\[Hamburger menu icon with three horizontal lines.\]](http://docs.aws.amazon.com/documentdb/latest/developerguide/images/docdb-menu-icon.png)) in the upper-left corner of the page.

1. In the **Parameter groups** pane, choose the cluster parameter group that is associated with your cluster. To identify the cluster parameter group that is associated with your cluster, see [Determining an Amazon DocumentDB cluster's parameter group](cluster_parameter_groups-describe.md#cluster_parameter_groups-determine). 

1. The resulting page shows the parameters and their corresponding details for your cluster parameter group. Select the parameter `change_stream_log_retention_duration`.

1. On the top right of the page, choose **Edit** to change the value of the parameter. The `change_stream_log_retention_duration` parameter can be modified to be between 1 hour and 7 days.

1. Make your change, and then choose **Modify cluster parameter** to save the changes. To discard your changes, choose **Cancel**.

------
#### [ Using the AWS CLI ]

To modify your cluster parameter group's `change_stream_log_retention_duration` parameter, use the `modify-db-cluster-parameter-group` operation with the following parameters:
+ **--db-cluster-parameter-group-name** — Required. The name of the cluster parameter group that you are modifying. To identify the cluster parameter group that is associated with your cluster, see [Determining an Amazon DocumentDB cluster's parameter group](cluster_parameter_groups-describe.md#cluster_parameter_groups-determine). 
+ **--parameters** — Required. The parameter that you are modifying. Each parameter entry must include the following: 
  + **ParameterName** — The name of the parameter that you are modifying. In this case, it is `change_stream_log_retention_duration` 
  + **ParameterValue** — The new value for this parameter. 
  + **ApplyMethod** — How you want changes to this parameter applied. Permitted values are `immediate` and `pending-reboot`. 
**Note**  
Parameters with the `ApplyType` of `static` must have an `ApplyMethod` of `pending-reboot`. 

1. To change the values of the parameter `change_stream_log_retention_duration`, run the following command and replace `parameter-value` with the value you want to modify the parameter to. 

   For Linux, macOS, or Unix:

   ```
   aws docdb modify-db-cluster-parameter-group \
       --db-cluster-parameter-group-name sample-parameter-group \
       --parameters "ParameterName=change_stream_log_retention_duration,ParameterValue=<parameter-value>,ApplyMethod=immediate"
   ```

   For Windows:

   ```
   aws docdb modify-db-cluster-parameter-group ^
       --db-cluster-parameter-group-name sample-parameter-group ^
       --parameters "ParameterName=change_stream_log_retention_duration,ParameterValue=<parameter-value>,ApplyMethod=immediate"
   ```

   Output from this operation looks something like the following (JSON format).

   ```
   {
       "DBClusterParameterGroupName": "sample-parameter-group"
   }
   ```

1. Wait at least 5 minutes.

1. List the parameter values of `sample-parameter-group` to ensure that your changes have been made. 

   For Linux, macOS, or Unix:

   ```
   aws docdb describe-db-cluster-parameters \
       --db-cluster-parameter-group-name sample-parameter-group
   ```

   For Windows:

   ```
   aws docdb describe-db-cluster-parameters ^
       --db-cluster-parameter-group-name sample-parameter-group
   ```

   Output from this operation looks something like the following (JSON format).

   ```
   {
       "Parameters": [
           {
               "ParameterName": "audit_logs",
               "ParameterValue": "disabled",
               "Description": "Enables auditing on cluster.",
               "Source": "system",
               "ApplyType": "dynamic",
               "DataType": "string",
               "AllowedValues": "enabled,disabled",
               "IsModifiable": true,
               "ApplyMethod": "pending-reboot"
           },
           {
               "ParameterName": "change_stream_log_retention_duration",
               "ParameterValue": "12345",
               "Description": "Duration of time in seconds that the change stream log is retained and can be consumed.",
               "Source": "user",
               "ApplyType": "dynamic",
               "DataType": "integer",
               "AllowedValues": "3600-86400",
               "IsModifiable": true,
               "ApplyMethod": "immediate"
           }
       ]
   }
   ```

------

**Note**  
Change stream log retention will not delete logs older than the configured `change_stream_log_retention_duration` value until log size is greater than (>) 51,200MB.

## Using change streams on secondary instances
<a name="change-streams-secondary-instances"></a>

To get started on using change stream on secondary instances, open the change stream cursor with `readPreference` as the secondary.

You can open a change stream cursor to watch for change events on a specific collection or all collections in a cluster or database. You can open a change stream cursor on any Amazon DocumentDB instance and fetch change stream documents from both writer and reader instances. You can share change stream tokens (such as `resumeToken` or `startOperationTime`) across different change stream cursors opened on a writer and reader instance.

**Example**

```
import os
import sys
from pymongo import MongoClient, ReadPreference
      
username = "DocumentDBusername"
password = <Your password> 

clusterendpoint = "DocumentDBClusterEndpoint"

client = MongoClient(clusterendpoint, username=username, password=password, tls='true', tlsCAFile='global-bundle.pem')

db = client['bar']
 
# Make sure to use SECONDARY to redirect cursor reads from secondary instances
coll = db.get_collection('foo', read_preference=ReadPreference.SECONDARY)

# Create a stream object on RO. The token needs to generated from PRIMARY.
stream = coll.watch(resumeAfter=token)

for event in stream:
   print(event)
```

**Guidelines and limitations for change streams on secondary instances**
+ Change stream events need to be replicated from the primary instance to the secondary instances. You can monitor the lag from the `DBInstanceReplicaLag` metric in Amazon CloudWatch.
+ Timestamps on secondary instances may not always be in sync with the primary instance. In this case, expect delays on the secondary instance timestamp so it can catch up. As a best practice, we recommend using `startAtOperationTime` or `resumeToken` to start the watch on the secondary instance.
+ You might experience lower throughput on secondary instances compared to the primary instance if your document size is large, you are doing `fullDocumentLookup`, and there is high concurrent write workload on the primary instance. As a best practice, we recommend you monitor your buffer cache hit ratio on the secondary and make sure that buffer cache hit ratio is high.

# Using Collation in Amazon DocumentDB 8.0
<a name="collation"></a>

Amazon DocumentDB 8.0 now supports collation. Collation allows you to configure language-specific rules for string comparison. With collation, you can specify rules for case-sensitive comparisons, or specify a language locale. Collation can be configured at the collection-level or index-level in DocumentDB 8.0. When you use collation in DocumentDB, internally a collation document is created with the following parameters. 

```
{
locale: string,
caseLevel: boolean,
caseFirst: string,
strength: int,
numericOrdering: boolean,
alternate: string,
maxVariable: string,
backwards: boolean,
normalization: boolean
}
```

## Limitations
<a name="collation-limitations"></a>

Collation has following limitations in Amazon DocumentDB:
+ Collation is compatible with planner v3 available in Amazon DocumentDB 8.0. Switching to plannerv2 or plannerv1 may cause inconsistent behaviors, including “Index not found“ errors.
+ Due to inherent library differences, if a mongodb collection with collation is exported, you will need to update the metadata.bson files and change its version from 57.1 to 60.2 prior to migration.
+ In rare cases, your collation settings may breach the internal limit on character count, causing the below error. "Error: Collation document has non-default attributes more than supported. Please reduce the number of options." In this case, try to reduce the options you provide in the collation document, or alternatively you could try and use default values wherever possible.

# Using Views in Amazon DocumentDB 8.0
<a name="views"></a>
+ Amazon DocumentDB 8.0 now supports views. Views function as virtual collections that present data based on specified aggregation operations. When you create a view, you define a query that transforms data from one or more source collections. Amazon DocumentDB 8.0 executes this query each time the view is accessed, without consuming additional storage resources. Unlike standard collections, views in Amazon DocumentDB 8.0 do not store documents on disk, making them an efficient solution for presenting transformed or filtered data to applications. To create a view in Amazon DocumentDB, you can use the createView command or the db.createView() helper method: 

  ```
  db.createView("viewName","sourceCollection",
  [
      { $match: { status: "active" } },
      { $project: { _id: 1, name: 1, email: 1 } }
  ]
  )
  ```

  This creates a view named "viewName" based on "sourceCollection" that only includes active documents and projects only the \$1id, name, and email fields. Views in Amazon DocumentDB are read-only. Write operations on views will return an error. For optimal performance with large datasets, you can structure your view pipelines to maximize efficiency. For complex aggregation pipelines, it's recommended to use the \$1match stage as the first stage or early in the pipeline to reduce the number of documents subsequent stages need to process, thus improving query performance. 

## Best Practices
<a name="views-bestpractices"></a>

Some best practices to follow with Views are listed below.
+ Filter Early: Use \$1match stages early in view pipelines to reduce the amount of data processed.
+ Avoid Complex Aggregations: For frequently accessed views with complex aggregations, consider creating a separate collection with precomputed results that are updated periodically.
+ Index Planning: Ensure that fields used in view pipelines, especially in \$1match and \$1sort operations, are properly indexed on the source collection.
+ Query Optimization: Use the explain command to understand how your view queries are executed and optimize accordingly.
+ Alternatives for Views: Given the functional differences between Amazon DocumentDB and MongoDB views, consider using regular collections with scheduled updates as an alternative to views when encountering limitations.

## Aggregator Operator Compatibility
<a name="views-aggregators"></a>

Amazon DocumentDB supports many aggregation operators in view definitions while continuing to expand compatibility. When using views, focus on these supported operators:
+ \$1match for filtering documents
+ \$1project for field selection and transformation
+ \$1addFields for adding computed fields
+ \$1sort for ordering results
+ \$1limit and \$1skip for pagination

Some specialized operators like \$1currentOp, \$1replaceRoot, and \$1geoNear currently work in direct aggregation queries rather than view definitions.

## Leveraging Indexes and Views
<a name="views-indexes"></a>

Views in Amazon DocumentDB 8.0 use the indexes of the underlying collection. As a result, you cannot create, drop, or rebuild indexes on a view directly. However, well-designed indexes on the source collection can significantly improve view query performance Below are some steps to optimize query performance on views:
+ Ensure appropriate indexes exist on the source collection fields used in the view's pipeline, especially in \$1match and \$1sort operations
+ Use the explain() method to analyze query execution plans and verify index usage. E.g., `db.viewName.find({...}).explain() `

# Using AWS Lambda with change streams
<a name="using-lambda"></a>

Amazon DocumentDB is integrated with AWS Lambda so you can use Lambda functions to process records in a change stream. Lambda event source mapping is a resource that can be used to invoke Lambda functions in order to process Amazon DocumentDB events that don’t directly invoke Lambda. With Amazon DocumentDB change stream as an event source, you can build event-driven applications that respond to changes in your data. For example, you can use Lambda functions to process new documents, track updates to existing documents, or log deleted documents.

You can configure an event source mapping to send records from your Amazon DocumentDB change stream to a Lambda function. Events can be sent one at a time or batched for improved efficiency and will processed in-order. You can configure your event source mapping’s batching behavior based on a specific time window duration (0 - 300 sec) or batch record count (max limit of 10,000 records). You can create multiple event source mappings to process the same data with multiple Lambda functions, or to process distinct items from multiple streams with a single function.

If your function returns an error, Lambda retries the batch until it processes successfully. In case the events in the change stream have expired, Lambda will disable the event source mapping. In this case, you can create a new event source mapping and configure it with a starting position of your choice. Lambda event source mappings process events at least once due to the distributed nature of its pollers. As a result, your Lambda function may receive duplicate events in rare situations. Follow best practices for working with AWS Lambda functions and build idempotent functions to avoid issues related to duplicate events. For more information see [Using AWS Lambda console with Amazon DocumentDB](https://docs.aws.amazon.com/lambda/latest/dg/with-documentdb.html) in the *AWS Lambda Developer Guide*.

As performance best practices, the Lambda function needs to be short lived. To avoid introducing unnecessary processing delays, it also should not execute complex logic. For a high velocity stream in particular, it is better to trigger an asynchronous post-processing step function workflows than synchronous long running Lambdas. For more information about AWS Lambda, see the [AWS Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html). 

## Limitations
<a name="lambda-limitations"></a>

The following are limitations to consider when working with Amazon DocumentDB and AWS Lambda:
+ AWS Lambda is currently supported only on Amazon DocumentDB 4.0 and 5.0.
+ AWS Lambda is not currently supported on elastic clusters or global clusters.
+ AWS Lambda payload sizes cannot exceed 6MB. For more information about Lambda batch sizes, see “Batching behavior” in [Lambda event source mappings](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html#invocation-eventsourcemapping-batching) section in the *AWS Lambda Developer Guide*.