|
| 1 | +--- |
| 2 | +title: Get started using Azure Cosmos DB API for MongoDB and Python |
| 3 | +description: Presents a Python code sample you can use to connect to and query using Azure Cosmos DB's API for MongoDB. |
| 4 | +author: gahl-levy |
| 5 | +ms.author: gahllevy |
| 6 | +ms.service: cosmos-db |
| 7 | +ms.subservice: cosmosdb-mongo |
| 8 | + |
| 9 | +ms.topic: quickstart |
| 10 | +ms.date: 10/22/2021 |
| 11 | +--- |
| 12 | + |
| 13 | +# Quickstart: Get started using Azure Cosmos DB API for MongoDB and Python |
| 14 | +[!INCLUDE[appliesto-mongodb-api](../includes/appliesto-mongodb-api.md)] |
| 15 | + |
| 16 | +> [!div class="op_single_selector"] |
| 17 | +> * [.NET](create-mongodb-dotnet.md) |
| 18 | +> * [Python](create-mongodb-python.md) |
| 19 | +> * [Java](create-mongodb-java.md) |
| 20 | +> * [Node.js](create-mongodb-nodejs.md) |
| 21 | +> * [Xamarin](create-mongodb-xamarin.md) |
| 22 | +> * [Golang](create-mongodb-go.md) |
| 23 | +> |
| 24 | +
|
| 25 | +This [quickstart](https://github.com/Azure-Samples/azure-cosmos-db-mongodb-python-getting-started) demonstrates how to: |
| 26 | +1. Create an [Azure Cosmos DB API for MongoDB account](mongodb-introduction.md) |
| 27 | +2. Connect to your account using PyMongo |
| 28 | +3. Create a sample database and collection |
| 29 | +4. Perform CRUD operations in the sample collection |
| 30 | + |
| 31 | +## Prerequisites to run the sample app |
| 32 | + |
| 33 | +* [Python](https://www.python.org/downloads/) 3.9+ (It's best to run the [sample code](https://github.com/Azure-Samples/azure-cosmos-db-mongodb-python-getting-started) described in this article with this recommended version. Although it may work on older versions of Python 3.) |
| 34 | +* [PyMongo](https://pypi.org/project/pymongo/) installed on your machine |
| 35 | + |
| 36 | +<a id="create-account"></a> |
| 37 | +## Create a database account |
| 38 | + |
| 39 | +[!INCLUDE [cosmos-db-create-dbaccount](../includes/cosmos-db-create-dbaccount-mongodb.md)] |
| 40 | + |
| 41 | +## Learn the object model |
| 42 | + |
| 43 | +Before you continue building the application, let's look into the hierarchy of resources in the API for MongoDB and the object model that's used to create and access these resources. The API for MongoDB creates resources in the following order: |
| 44 | + |
| 45 | +* Azure Cosmos DB API for MongoDB account |
| 46 | +* Databases |
| 47 | +* Collections |
| 48 | +* Documents |
| 49 | + |
| 50 | +To learn more about the hierarchy of entities, see the [Azure Cosmos DB resource model](../account-databases-containers-items.md) article. |
| 51 | + |
| 52 | +## Get the code |
| 53 | + |
| 54 | +Download the sample Python code [from the repository](https://github.com/Azure-Samples/azure-cosmos-db-mongodb-python-getting-started) or use git clone: |
| 55 | + |
| 56 | +```shell |
| 57 | +git clone https://github.com/Azure-Samples/azure-cosmos-db-mongodb-python-getting-started |
| 58 | +``` |
| 59 | + |
| 60 | +## Retrieve your connection string |
| 61 | + |
| 62 | +When running the sample code, you have to enter your API for MongoDB account's connection string. Use the following steps to find it: |
| 63 | + |
| 64 | +1. In the [Azure portal](https://portal.azure.com/), select your Cosmos DB account. |
| 65 | + |
| 66 | +2. In the left navigation select **Connection String**, and then select **Read-write Keys**. You'll use the copy buttons on the right side of the screen to copy the primary connection string. |
| 67 | + |
| 68 | +> [!WARNING] |
| 69 | +> Never check passwords or other sensitive data into source code. |
| 70 | +
|
| 71 | + |
| 72 | +## Run the code |
| 73 | + |
| 74 | +```shell |
| 75 | +python run.py |
| 76 | +``` |
| 77 | + |
| 78 | +## Understand how it works |
| 79 | + |
| 80 | +### Connecting |
| 81 | + |
| 82 | +The following code prompts the user for the connection string. It's never a good idea to have your connection string in code since it enables anyone with it to read or write to your database. |
| 83 | + |
| 84 | +```python |
| 85 | +CONNECTION_STRING = getpass.getpass(prompt='Enter your primary connection string: ') # Prompts user for connection string |
| 86 | +``` |
| 87 | + |
| 88 | +The following code creates a client connection your API for MongoDB and tests to make sure it's valid. |
| 89 | + |
| 90 | +```python |
| 91 | +client = pymongo.MongoClient(CONNECTION_STRING) |
| 92 | +try: |
| 93 | + client.server_info() # validate connection string |
| 94 | +except pymongo.errors.ServerSelectionTimeoutError: |
| 95 | + raise TimeoutError("Invalid API for MongoDB connection string or timed out when attempting to connect") |
| 96 | +``` |
| 97 | + |
| 98 | +### Resource creation |
| 99 | +The following code creates the sample database and collection that will be used to perform CRUD operations. When creating resources programmatically, it's recommended to use the API for MongoDB extension commands (as shown here) because these commands have the ability to set the resource throughput (RU/s) and configure sharding. |
| 100 | + |
| 101 | +Implicitly creating resources will work but will default to recommended values for throughput and will not be sharded. |
| 102 | + |
| 103 | +```python |
| 104 | +# Database with 400 RU throughput that can be shared across the DB's collections |
| 105 | +db.command({'customAction': "CreateDatabase", 'offerThroughput': 400}) |
| 106 | +``` |
| 107 | + |
| 108 | +```python |
| 109 | + # Creates a unsharded collection that uses the DBs shared throughput |
| 110 | +db.command({'customAction': "CreateCollection", 'collection': UNSHARDED_COLLECTION_NAME}) |
| 111 | +``` |
| 112 | + |
| 113 | +### Writing a document |
| 114 | +The following inserts a sample document we will continue to use throughout the sample. We get its unique _id field value so that we can query it in subsequent operations. |
| 115 | + |
| 116 | +```python |
| 117 | +"""Insert a sample document and return the contents of its _id field""" |
| 118 | +document_id = collection.insert_one({SAMPLE_FIELD_NAME: randint(50, 500)}).inserted_id |
| 119 | +``` |
| 120 | + |
| 121 | +### Reading/Updating a document |
| 122 | +The following queries, updates, and again queries for the document that we previously inserted. |
| 123 | + |
| 124 | +```python |
| 125 | +print("Found a document with _id {}: {}".format(document_id, collection.find_one({"_id": document_id}))) |
| 126 | + |
| 127 | +collection.update_one({"_id": document_id}, {"$set":{SAMPLE_FIELD_NAME: "Updated!"}}) |
| 128 | +print("Updated document with _id {}: {}".format(document_id, collection.find_one({"_id": document_id}))) |
| 129 | +``` |
| 130 | + |
| 131 | +### Deleting a document |
| 132 | +Lastly, we delete the document we created from the collection. |
| 133 | +```python |
| 134 | +"""Delete the document containing document_id from the collection""" |
| 135 | +collection.delete_one({"_id": document_id}) |
| 136 | +``` |
| 137 | + |
| 138 | +## Next steps |
| 139 | +In this quickstart, you've learned how to create an API for MongoDB account, create a database and a collection with code, and perform CRUD operations. |
| 140 | + |
| 141 | +Trying to do capacity planning for a migration to Azure Cosmos DB? You can use information about your existing database cluster for capacity planning. |
| 142 | +* If all you know is the number of vcores and servers in your existing database cluster, read about [estimating request units using vCores or vCPUs](../convert-vcore-to-request-unit.md) |
| 143 | +* If you know typical request rates for your current database workload, read about [estimating request units using Azure Cosmos DB capacity planner](estimate-ru-capacity-planner.md) |
| 144 | + |
| 145 | +> [!div class="nextstepaction"] |
| 146 | +> [Import MongoDB data into Azure Cosmos DB](../../dms/tutorial-mongodb-cosmos-db.md?toc=%2fazure%2fcosmos-db%2ftoc.json%253ftoc%253d%2fazure%2fcosmos-db%2ftoc.json) |
0 commit comments