Manage Azure Cosmos DB for MongoDB resources using Azure Resource Manager templates

APPLIES TO: MongoDB

In this article, you learn how to use Azure Resource Manager templates to help deploy and manage your Azure Cosmos DB accounts for API for MongoDB, databases, and collections.

This article has examples for Azure Cosmos DB's API for MongoDB only, to find examples for other API type accounts see: use Azure Resource Manager templates with Azure Cosmos DB's API for Cassandra, Gremlin, SQL, Table articles.

Important

  • Account names are limited to 44 characters, all lowercase.
  • To change the throughput values, redeploy the template with updated RU/s.
  • When you add or remove locations to an Azure Cosmos DB account, you can't simultaneously modify other properties. These operations must be done separately.

To create any of the Azure Cosmos DB resources below, copy the following example template into a new json file. You can optionally create a parameters json file to use when deploying multiple instances of the same resource with different names and values. There are many ways to deploy Azure Resource Manager templates including, Azure portal, Azure CLI, Azure PowerShell and GitHub.

Azure Cosmos DB account for MongoDB with autoscale provisioned throughput

This template will create an Azure Cosmos DB account for API for MongoDB (3.2, 3.6, 4.0 and 4.2) with two collections that share autoscale throughput at the database level. This template is also available for one-click deploy from Azure Quickstart Templates Gallery.

Deploy to Azure

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.3.539.46024",
      "templateHash": "1468643375910708237"
    }
  },
  "parameters": {
    "accountName": {
      "type": "string",
      "defaultValue": "[format('mongodb-{0}', uniqueString(resourceGroup().id))]",
      "metadata": {
        "description": "Cosmos DB account name"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for the Cosmos DB account."
      }
    },
    "primaryRegion": {
      "type": "string",
      "metadata": {
        "description": "The primary replica region for the Cosmos DB account."
      }
    },
    "secondaryRegion": {
      "type": "string",
      "metadata": {
        "description": "The secondary replica region for the Cosmos DB account."
      }
    },
    "serverVersion": {
      "type": "string",
      "defaultValue": "4.0",
      "allowedValues": [
        "3.2",
        "3.6",
        "4.0"
      ],
      "metadata": {
        "description": "Specifies the MongoDB server version to use."
      }
    },
    "defaultConsistencyLevel": {
      "type": "string",
      "defaultValue": "Session",
      "allowedValues": [
        "Eventual",
        "ConsistentPrefix",
        "Session",
        "BoundedStaleness",
        "Strong"
      ],
      "metadata": {
        "description": "The default consistency level of the Cosmos DB account."
      }
    },
    "maxStalenessPrefix": {
      "type": "int",
      "defaultValue": 100000,
      "maxValue": 2147483647,
      "minValue": 10,
      "metadata": {
        "description": "Max stale requests. Required for BoundedStaleness. Valid ranges, Single Region: 10 to 1000000. Multi Region: 100000 to 1000000."
      }
    },
    "maxIntervalInSeconds": {
      "type": "int",
      "defaultValue": 300,
      "maxValue": 86400,
      "minValue": 5,
      "metadata": {
        "description": "Max lag time (seconds). Required for BoundedStaleness. Valid ranges, Single Region: 5 to 84600. Multi Region: 300 to 86400."
      }
    },
    "databaseName": {
      "type": "string",
      "metadata": {
        "description": "The name for the Mongo DB database"
      }
    },
    "collection1Name": {
      "type": "string",
      "metadata": {
        "description": "The name for the first Mongo DB collection"
      }
    },
    "collection2Name": {
      "type": "string",
      "metadata": {
        "description": "The name for the second Mongo DB collection"
      }
    },
    "autoscaleMaxThroughput": {
      "type": "int",
      "defaultValue": 4000,
      "maxValue": 1000000,
      "minValue": 4000,
      "metadata": {
        "description": "Maximum throughput when using Autoscale Throughput Policy for the Database"
      }
    }
  },
  "functions": [],
  "variables": {
    "accountName_var": "[toLower(parameters('accountName'))]",
    "consistencyPolicy": {
      "Eventual": {
        "defaultConsistencyLevel": "Eventual"
      },
      "ConsistentPrefix": {
        "defaultConsistencyLevel": "ConsistentPrefix"
      },
      "Session": {
        "defaultConsistencyLevel": "Session"
      },
      "BoundedStaleness": {
        "defaultConsistencyLevel": "BoundedStaleness",
        "maxStalenessPrefix": "[parameters('maxStalenessPrefix')]",
        "maxIntervalInSeconds": "[parameters('maxIntervalInSeconds')]"
      },
      "Strong": {
        "defaultConsistencyLevel": "Strong"
      }
    },
    "locations": [
      {
        "locationName": "[parameters('primaryRegion')]",
        "failoverPriority": 0,
        "isZoneRedundant": false
      },
      {
        "locationName": "[parameters('secondaryRegion')]",
        "failoverPriority": 1,
        "isZoneRedundant": false
      }
    ]
  },
  "resources": [
    {
      "type": "Microsoft.DocumentDB/databaseAccounts",
      "apiVersion": "2021-04-15",
      "name": "[variables('accountName_var')]",
      "location": "[parameters('location')]",
      "kind": "MongoDB",
      "properties": {
        "consistencyPolicy": "[variables('consistencyPolicy')[parameters('defaultConsistencyLevel')]]",
        "locations": "[variables('locations')]",
        "databaseAccountOfferType": "Standard",
        "apiProperties": {
          "serverVersion": "[parameters('serverVersion')]"
        }
      }
    },
    {
      "type": "Microsoft.DocumentDB/databaseAccounts/mongodbDatabases",
      "apiVersion": "2021-04-15",
      "name": "[format('{0}/{1}', variables('accountName_var'), parameters('databaseName'))]",
      "properties": {
        "resource": {
          "id": "[parameters('databaseName')]"
        },
        "options": {
          "autoscaleSettings": {
            "maxThroughput": "[parameters('autoscaleMaxThroughput')]"
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.DocumentDB/databaseAccounts', variables('accountName_var'))]"
      ]
    },
    {
      "type": "Microsoft.DocumentDb/databaseAccounts/mongodbDatabases/collections",
      "apiVersion": "2021-04-15",
      "name": "[format('{0}/{1}/{2}', variables('accountName_var'), parameters('databaseName'), parameters('collection1Name'))]",
      "properties": {
        "resource": {
          "id": "[parameters('collection1Name')]",
          "shardKey": {
            "user_id": "Hash"
          },
          "indexes": [
            {
              "key": {
                "keys": [
                  "_id"
                ]
              }
            },
            {
              "key": {
                "keys": [
                  "$**"
                ]
              }
            },
            {
              "key": {
                "keys": [
                  "user_id",
                  "user_address"
                ]
              },
              "options": {
                "unique": true
              }
            },
            {
              "key": {
                "keys": [
                  "_ts"
                ],
                "options": {
                  "expireAfterSeconds": 2629746
                }
              }
            }
          ],
          "options": {
            "If-Match": "<ETag>"
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.DocumentDB/databaseAccounts/mongodbDatabases', variables('accountName_var'), parameters('databaseName'))]",
        "[resourceId('Microsoft.DocumentDB/databaseAccounts', variables('accountName_var'))]"
      ]
    },
    {
      "type": "Microsoft.DocumentDb/databaseAccounts/mongodbDatabases/collections",
      "apiVersion": "2021-04-15",
      "name": "[format('{0}/{1}/{2}', variables('accountName_var'), parameters('databaseName'), parameters('collection2Name'))]",
      "properties": {
        "resource": {
          "id": "[parameters('collection2Name')]",
          "shardKey": {
            "company_id": "Hash"
          },
          "indexes": [
            {
              "key": {
                "keys": [
                  "_id"
                ]
              }
            },
            {
              "key": {
                "keys": [
                  "$**"
                ]
              }
            },
            {
              "key": {
                "keys": [
                  "company_id",
                  "company_address"
                ]
              },
              "options": {
                "unique": true
              }
            },
            {
              "key": {
                "keys": [
                  "_ts"
                ],
                "options": {
                  "expireAfterSeconds": 2629746
                }
              }
            }
          ],
          "options": {
            "If-Match": "<ETag>"
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.DocumentDB/databaseAccounts/mongodbDatabases', variables('accountName_var'), parameters('databaseName'))]",
        "[resourceId('Microsoft.DocumentDB/databaseAccounts', variables('accountName_var'))]"
      ]
    }
  ]
}

Azure Cosmos DB account for MongoDB with standard provisioned throughput

This template will create an Azure Cosmos DB account for API for MongoDB (3.2, 3.6, 4.0 and 4.2) with two collections that share 400 RU/s standard (manual) throughput at the database level. This template is also available for one-click deploy from Azure Quickstart Templates Gallery.

Deploy to Azure

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.3.539.46024",
      "templateHash": "1202222167196775397"
    }
  },
  "parameters": {
    "accountName": {
      "type": "string",
      "defaultValue": "[format('mongodb-{0}', uniqueString(resourceGroup().id))]",
      "metadata": {
        "description": "Cosmos DB account name"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for the Cosmos DB account."
      }
    },
    "primaryRegion": {
      "type": "string",
      "metadata": {
        "description": "The primary replica region for the Cosmos DB account."
      }
    },
    "secondaryRegion": {
      "type": "string",
      "metadata": {
        "description": "The secondary replica region for the Cosmos DB account."
      }
    },
    "defaultConsistencyLevel": {
      "type": "string",
      "defaultValue": "Session",
      "allowedValues": [
        "Eventual",
        "ConsistentPrefix",
        "Session",
        "BoundedStaleness",
        "Strong"
      ],
      "metadata": {
        "description": "The default consistency level of the Cosmos DB account."
      }
    },
    "serverVersion": {
      "type": "string",
      "defaultValue": "4.0",
      "allowedValues": [
        "3.2",
        "3.6",
        "4.0"
      ],
      "metadata": {
        "description": "Specifies the MongoDB server version to use."
      }
    },
    "maxStalenessPrefix": {
      "type": "int",
      "defaultValue": 100000,
      "maxValue": 2147483647,
      "minValue": 10,
      "metadata": {
        "description": "Max stale requests. Required for BoundedStaleness. Valid ranges, Single Region: 10 to 1000000. Multi Region: 100000 to 1000000."
      }
    },
    "maxIntervalInSeconds": {
      "type": "int",
      "defaultValue": 300,
      "maxValue": 86400,
      "minValue": 5,
      "metadata": {
        "description": "Max lag time (seconds). Required for BoundedStaleness. Valid ranges, Single Region: 5 to 84600. Multi Region: 300 to 86400."
      }
    },
    "databaseName": {
      "type": "string",
      "metadata": {
        "description": "The name for the Mongo DB database"
      }
    },
    "throughput": {
      "type": "int",
      "defaultValue": 400,
      "maxValue": 1000000,
      "minValue": 400,
      "metadata": {
        "description": "The shared throughput for the Mongo DB database"
      }
    },
    "collection1Name": {
      "type": "string",
      "metadata": {
        "description": "The name for the first Mongo DB collection"
      }
    },
    "collection2Name": {
      "type": "string",
      "metadata": {
        "description": "The name for the second Mongo DB collection"
      }
    }
  },
  "functions": [],
  "variables": {
    "accountName_var": "[toLower(parameters('accountName'))]",
    "consistencyPolicy": {
      "Eventual": {
        "defaultConsistencyLevel": "Eventual"
      },
      "ConsistentPrefix": {
        "defaultConsistencyLevel": "ConsistentPrefix"
      },
      "Session": {
        "defaultConsistencyLevel": "Session"
      },
      "BoundedStaleness": {
        "defaultConsistencyLevel": "BoundedStaleness",
        "maxStalenessPrefix": "[parameters('maxStalenessPrefix')]",
        "maxIntervalInSeconds": "[parameters('maxIntervalInSeconds')]"
      },
      "Strong": {
        "defaultConsistencyLevel": "Strong"
      }
    },
    "locations": [
      {
        "locationName": "[parameters('primaryRegion')]",
        "failoverPriority": 0,
        "isZoneRedundant": false
      },
      {
        "locationName": "[parameters('secondaryRegion')]",
        "failoverPriority": 1,
        "isZoneRedundant": false
      }
    ]
  },
  "resources": [
    {
      "type": "Microsoft.DocumentDB/databaseAccounts",
      "apiVersion": "2021-04-15",
      "name": "[variables('accountName_var')]",
      "location": "[parameters('location')]",
      "kind": "MongoDB",
      "properties": {
        "consistencyPolicy": "[variables('consistencyPolicy')[parameters('defaultConsistencyLevel')]]",
        "locations": "[variables('locations')]",
        "databaseAccountOfferType": "Standard",
        "apiProperties": {
          "serverVersion": "[parameters('serverVersion')]"
        }
      }
    },
    {
      "type": "Microsoft.DocumentDB/databaseAccounts/mongodbDatabases",
      "apiVersion": "2021-04-15",
      "name": "[format('{0}/{1}', variables('accountName_var'), parameters('databaseName'))]",
      "properties": {
        "resource": {
          "id": "[parameters('databaseName')]"
        },
        "options": {
          "throughput": "[parameters('throughput')]"
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.DocumentDB/databaseAccounts', variables('accountName_var'))]"
      ]
    },
    {
      "type": "Microsoft.DocumentDb/databaseAccounts/mongodbDatabases/collections",
      "apiVersion": "2021-04-15",
      "name": "[format('{0}/{1}', format('{0}/{1}', variables('accountName_var'), parameters('databaseName')), parameters('collection1Name'))]",
      "properties": {
        "resource": {
          "id": "[parameters('collection1Name')]",
          "shardKey": {
            "user_id": "Hash"
          },
          "indexes": [
            {
              "key": {
                "keys": [
                  "_id"
                ]
              }
            },
            {
              "key": {
                "keys": [
                  "$**"
                ]
              }
            },
            {
              "key": {
                "keys": [
                  "user_id",
                  "user_address"
                ]
              },
              "options": {
                "unique": true
              }
            },
            {
              "key": {
                "keys": [
                  "_ts"
                ]
              },
              "options": {
                "expireAfterSeconds": 2629746
              }
            }
          ],
          "options": {
            "If-Match": "<ETag>"
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.DocumentDB/databaseAccounts/mongodbDatabases', split(format('{0}/{1}', variables('accountName_var'), parameters('databaseName')), '/')[0], split(format('{0}/{1}', variables('accountName_var'), parameters('databaseName')), '/')[1])]"
      ]
    },
    {
      "type": "Microsoft.DocumentDb/databaseAccounts/mongodbDatabases/collections",
      "apiVersion": "2021-04-15",
      "name": "[format('{0}/{1}', format('{0}/{1}', variables('accountName_var'), parameters('databaseName')), parameters('collection2Name'))]",
      "properties": {
        "resource": {
          "id": "[parameters('collection2Name')]",
          "shardKey": {
            "company_id": "Hash"
          },
          "indexes": [
            {
              "key": {
                "keys": [
                  "_id"
                ]
              }
            },
            {
              "key": {
                "keys": [
                  "$**"
                ]
              }
            },
            {
              "key": {
                "keys": [
                  "company_id",
                  "company_address"
                ]
              },
              "options": {
                "unique": true
              }
            },
            {
              "key": {
                "keys": [
                  "_ts"
                ]
              },
              "options": {
                "expireAfterSeconds": 2629746
              }
            }
          ],
          "options": {
            "If-Match": "<ETag>"
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.DocumentDB/databaseAccounts/mongodbDatabases', split(format('{0}/{1}', variables('accountName_var'), parameters('databaseName')), '/')[0], split(format('{0}/{1}', variables('accountName_var'), parameters('databaseName')), '/')[1])]"
      ]
    }
  ]
}

Next steps

Here are some additional resources: