Skip to content

Commit 1ae81d8

Browse files
authored
Merge pull request #218232 from vmagelo/python-get-started
Create new Python get-started article.
2 parents 413f3a2 + 3dfd74b commit 1ae81d8

File tree

4 files changed

+279
-1
lines changed

4 files changed

+279
-1
lines changed

articles/cosmos-db/mongodb/TOC.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,12 @@
344344
href: how-to-javascript-manage-documents.md
345345
- name: Manage queries
346346
href: how-to-javascript-manage-queries.md
347+
- name: Python
348+
items:
349+
- name: Get started
350+
href: how-to-python-get-started.md
351+
- name: Manage databases
352+
href: how-to-python-manage-databases.md
347353
- name: .NET
348354
items:
349355
- name: Get started
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
---
2+
title: Get started with Azure Cosmos DB for MongoDB and Python
3+
description: Get started developing a Python application that works with Azure Cosmos DB for MongoDB. This article helps you learn how to set up a project and configure access to an Azure Cosmos DB for MongoDB database.
4+
author: diberry
5+
ms.author: diberry
6+
ms.service: cosmos-db
7+
ms.reviewer: sidandrews
8+
ms.subservice: mongodb
9+
ms.devlang: python
10+
ms.topic: how-to
11+
ms.date: 11/16/2022
12+
ms.custom: devx-track-js, ignite-2022
13+
---
14+
15+
# Get started with Azure Cosmos DB for MongoDB and Python
16+
[!INCLUDE[MongoDB](../includes/appliesto-mongodb.md)]
17+
18+
This article shows you how to connect to Azure Cosmos DB for MongoDB using the PyMongo driver package. Once connected, you can perform operations on databases, collections, and docs.
19+
20+
> [!NOTE]
21+
> The [example code snippets](https://github.com/Azure-Samples/azure-cosmos-db-mongodb-python-getting-started) are available on GitHub as a Python project.
22+
23+
This article shows you how to communicate with the Azure Cosmos DB’s API for MongoDB by using one of the open-source MongoDB client drivers for Python, [PyMongo](https://www.mongodb.com/docs/drivers/pymongo/).
24+
25+
## Prerequisites
26+
27+
* An Azure account with an active subscription. [Create an account for free](https://azure.microsoft.com/free).
28+
* [Python 3.8+](https://www.python.org/downloads/)
29+
* [Azure Command-Line Interface (CLI)](/cli/azure/) or [Azure PowerShell](/powershell/azure/)
30+
* [Azure Cosmos DB for MongoDB resource](quickstart-python.md#create-an-azure-cosmos-db-account)
31+
32+
## Create a new Python app
33+
34+
1. Create a new empty folder using your preferred terminal and change directory to the folder.
35+
36+
> [!NOTE]
37+
> If you just want the finished code, download or fork and clone the [example code snippets](https://github.com/Azure-Samples/azure-cosmos-db-mongodb-python-getting-started) repo that has the full example. You can also `git clone` the repo in Azure Cloud Shell to walk through the steps shown in this quickstart.
38+
39+
2. Create a *requirements.txt* file that lists the [PyMongo](https://www.mongodb.com/docs/drivers/pymongo/) and [python-dotenv](https://pypi.org/project/python-dotenv/) packages. The `dotenv` package is used to read the environment variables from a `.env` file during local development.
40+
41+
```text
42+
# requirements.txt
43+
pymongo
44+
python-dotenv
45+
```
46+
47+
3. Create a virtual environment and install the packages.
48+
49+
#### [Windows](#tab/venv-windows)
50+
51+
```bash
52+
# py -3 uses the global python interpreter. You can also use python3 -m venv .venv.
53+
py -3 -m venv .venv
54+
source .venv/Scripts/activate
55+
pip install -r requirements.txt
56+
```
57+
58+
#### [Linux / macOS](#tab/venv-linux+macos)
59+
60+
```bash
61+
python3 -m venv .venv
62+
source .venv/bin/activate
63+
pip install -r requirements.txt
64+
```
65+
66+
---
67+
68+
## Connect with PyMongo driver to Azure Cosmos DB for MongoDB
69+
70+
To connect with the PyMongo driver to Azure Cosmos DB, create an instance of the [MongoClient](https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient) object. This class is the starting point to perform all operations against databases.
71+
72+
The most common constructor for **MongoClient** requires just the `host` parameter, which in this article is set to the `COSMOS_CONNECTION_STRING` environment variable. There are other optional parameters and keyword parameters you can use in the constructor. Many of the optional parameters can also be specified with the `host` parameter. If the same option is passed in with `host` and as a parameter, the parameter takes precedence.
73+
74+
Refer to the [Troubleshooting guide](error-codes-solutions.md) for connection issues.
75+
76+
## Get resource name
77+
78+
In the commands below, we show *msdocs-cosmos* as the resource group name. Change the name as appropriate for your situation.
79+
80+
### [Azure CLI](#tab/azure-cli)
81+
82+
[!INCLUDE [Azure CLI - get resource name](<./includes/azure-cli-get-resource-name.md>)]
83+
84+
### [PowerShell](#tab/azure-powershell)
85+
86+
[!INCLUDE [Powershell - set resource name](<./includes/powershell-set-resource-name.md>)]
87+
88+
### [Portal](#tab/azure-portal)
89+
90+
Skip this step and use the information for the portal in the next step.
91+
92+
---
93+
## Retrieve your connection string
94+
95+
### [Azure CLI](#tab/azure-cli)
96+
97+
[!INCLUDE [Azure CLI - get connection string](<./includes/azure-cli-get-connection-string.md>)]
98+
99+
### [PowerShell](#tab/azure-powershell)
100+
101+
[!INCLUDE [Powershell - get connection string](<./includes/powershell-get-connection-string.md>)]
102+
103+
### [Portal](#tab/azure-portal)
104+
105+
[!INCLUDE [Portal - get connection string](<./includes/portal-get-connection-string-from-sign-in.md>)]
106+
107+
---
108+
109+
## Configure environment variables
110+
111+
[!INCLUDE [Multitab - store connection string in environment variable](<./includes/environment-variables-connection-string.md>)]
112+
113+
## Create MongoClient with connection string
114+
115+
1. Add dependencies to reference the [PyMongo](https://www.mongodb.com/docs/drivers/pymongo/) and [python-dotenv](https://pypi.org/project/python-dotenv/) packages.
116+
117+
:::code language="python" source="~/azure-cosmos-db-mongodb-python-getting-started/101-client-connection-string/run.py" id="package_dependencies":::
118+
119+
2. Define a new instance of the `MongoClient` class using the constructor and the connection string read from an environment variable.
120+
121+
:::code language="python" source="~/azure-cosmos-db-mongodb-python-getting-started/101-client-connection-string/run.py" id="client_credentials":::
122+
123+
For more information on different ways to create a ``MongoClient`` instance, see [Making a Connection with MongoClient](https://pymongo.readthedocs.io/en/stable/tutorial.html#making-a-connection-with-mongoclient).
124+
125+
## Close the MongoClient connection
126+
127+
When your application is finished with the connection, remember to close it. That `.close()` call should be after all database calls are made.
128+
129+
```python
130+
client.close()
131+
```
132+
133+
## Use MongoDB client classes with Azure Cosmos DB for API for MongoDB
134+
135+
Let's look at 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:
136+
137+
* [MongoClient](https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html) - The first step when working with PyMongo is to create a MongoClient to connect to Azure Cosmos DB's API for MongoDB. The client object is used to configure and execute requests against the service.
138+
139+
* [Database](https://pymongo.readthedocs.io/en/stable/api/pymongo/database.html) - Azure Cosmos DB's API for MongoDB can support one or more independent databases.
140+
141+
* [Collection](https://pymongo.readthedocs.io/en/stable/api/pymongo/database.html) - A database can contain one or more collections. A collection is a group of documents stored in MongoDB, and can be thought of as roughly the equivalent of a table in a relational database.
142+
143+
* [Document](https://pymongo.readthedocs.io/en/stable/tutorial.html#documents) - A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection don't need to have the same set of fields or structure. And common fields in a collection's documents may hold different types of data.
144+
145+
To learn more about the hierarchy of entities, see the [Azure Cosmos DB resource model](../account-databases-containers-items.md) article.
146+
147+
## See also
148+
149+
- [PyPI Package](https://pypi.org/project/azure-cosmos/)
150+
- [API reference](https://www.mongodb.com/docs/drivers/python/)
151+
152+
## Next steps
153+
154+
Now that you've connected to an API for MongoDB account, use the next guide to create and manage databases.
155+
156+
> [!div class="nextstepaction"]
157+
> [Create a database in Azure Cosmos DB for MongoDB using Python](how-to-python-manage-databases.md)
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
---
2+
title: Manage a MongoDB database using Python
3+
description: Learn how to manage your Azure Cosmos DB resource when it provides the API for MongoDB with a Python SDK.
4+
author: diberry
5+
ms.author: diberry
6+
ms.service: cosmos-db
7+
ms.subservice: mongodb
8+
ms.devlang: python
9+
ms.topic: how-to
10+
ms.date: 11/15/2022
11+
ms.custom: devx-track-js, ignite-2022
12+
---
13+
14+
# Manage a MongoDB database using Python
15+
16+
[!INCLUDE[MongoDB](../includes/appliesto-mongodb.md)]
17+
18+
Your MongoDB server in Azure Cosmos DB is available from the common Python packages for MongoDB such as:
19+
20+
* [PyMongo](https://www.mongodb.com/docs/drivers/pymongo/) for synchronous Python applications and used in this article.
21+
* [Motor](https://www.mongodb.com/docs/drivers/motor/) for asynchronous Python applications.
22+
23+
> [!NOTE]
24+
> The [example code snippets](https://github.com/Azure-Samples/azure-cosmos-db-mongodb-python-getting-started) are available on GitHub as a Python project.
25+
26+
## Name a database
27+
28+
In Azure Cosmos DB, a database is analogous to a namespace. When you create a database, the database name forms a segment of the URI used to access the database resource and any child resources.
29+
30+
Here are some quick rules when naming a database:
31+
32+
* Keep database names between 3 and 63 characters long
33+
* Database names can only contain lowercase letters, numbers, or the dash (-) character.
34+
* Database names must start with a lowercase letter or number.
35+
36+
Once created, the URI for a database is in this format:
37+
38+
`https://<cosmos-account-name>.documents.azure.com/dbs/<database-name>`
39+
40+
## Get database instance
41+
42+
The database holds the collections and their documents. To access a database, use attribute style access or dictionary style access of the MongoClient. For more information, see [Getting a Database](https://pymongo.readthedocs.io/en/stable/tutorial.html#getting-a-database).
43+
44+
The following code snippets assume you've already created your [client connection](how-to-python-get-started.md#create-mongoclient-with-connection-string) and that you [close your client connection](how-to-python-get-started.md#close-the-mongoclient-connection) after these code snippets.
45+
46+
## Get server information
47+
48+
Access server info with the [server_info](https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.server_info) method of the MongoClient class. You don't need to specify the database name to get this information. The information returned is specific to MongoDB and doesn't represent the Azure Cosmos DB platform itself.
49+
50+
You can also list databases using the [MongoClient.list_database_names](https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.list_database_names) method and issue a [MongoDB command](https://www.mongodb.com/docs/manual/reference/command/nav-diagnostic/) to a database with the [MongoClient.db.command](https://pymongo.readthedocs.io/en/stable/api/pymongo/database.html#pymongo.database.Database.command) method.
51+
52+
:::code language="python" source="~/azure-cosmos-db-mongodb-python-getting-started/200-admin/run.py" id="server_info":::
53+
54+
The preceding code snippet displays output similar to the following example console output:
55+
56+
:::code language="python" source="~/azure-cosmos-db-mongodb-python-getting-started/200-admin/run.py" id="console_result":::
57+
58+
## Does database exist?
59+
60+
The PyMongo driver for Python creates a database if it doesn't exist when you access it. However, we recommend that instead you use the [MongoDB extension commands](/azure/cosmos-db/mongodb/custom-commands) to manage data stored in Azure Cosmos DB’s API for MongoDB. To create a new database if it doesn't exist, use the [create database extension](/azure/cosmos-db/mongodb/custom-commands#create-database) as shown in the following code snippet.
61+
62+
To see if the database already exists before using it, get the list of current databases with the [list_database_names](https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.list_database_names) method.
63+
64+
:::code language="python" source="~/azure-cosmos-db-mongodb-python-getting-started/201-does-database-exist/run.py" id="does_database_exist":::
65+
66+
The preceding code snippet displays output similar to the following example console output:
67+
68+
:::code language="console" source="~/azure-cosmos-db-mongodb-python-getting-started/201-does-database-exist/run.py" id="console_result":::
69+
70+
## Get list of databases, collections, and document count
71+
72+
When you manage your MongoDB server programmatically, it's helpful to know what databases and collections are on the server and how many documents in each collection. For more information, see:
73+
74+
* [Getting a database](https://pymongo.readthedocs.io/en/stable/tutorial.html#getting-a-database)
75+
* [Getting a collection](https://pymongo.readthedocs.io/en/stable/tutorial.html#getting-a-collection)
76+
* [Counting documents](https://pymongo.readthedocs.io/en/stable/tutorial.html#counting)
77+
78+
:::code language="python" source="~/azure-cosmos-db-mongodb-python-getting-started/202-get-doc-count/run.py" id="database_object":::
79+
80+
The preceding code snippet displays output similar to the following example console output:
81+
82+
:::code language="python" source="~/azure-cosmos-db-mongodb-python-getting-started/202-get-doc-count/run.py" id="console_result":::
83+
84+
## Get database object instance
85+
86+
If a database doesn't exist, the PyMongo driver for Python creates it when you access it. However, we recommend that instead you use the [MongoDB extension commands](/azure/cosmos-db/mongodb/custom-commands) to manage data stored in Azure Cosmos DB’s API for MongoDB. The pattern is shown above in the section [Does database exist?](#does-database-exist).
87+
88+
When working with PyMongo, you access databases using attribute style access on MongoClient instances. Once you have a database instance, you can use database level operations as shown below.
89+
90+
```python
91+
collections = client[db].list_collection_names()
92+
```
93+
94+
For an overview of working with databases using the PyMongo driver, see [Database level operations](https://pymongo.readthedocs.io/en/stable/api/pymongo/database.html#pymongo.database.Database).
95+
96+
97+
## Drop a database
98+
99+
A database is removed from the server using the [drop_database](https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient.drop_database) method of the MongoClient.
100+
101+
:::code language="python" source="~/azure-cosmos-db-mongodb-python-getting-started/300-drop-database/run.py" id="drop_database":::
102+
103+
The preceding code snippet displays output similar to the following example console output:
104+
105+
:::code language="console" source="~/azure-cosmos-db-mongodb-python-getting-started/300-drop-database/run.py" id="console_result":::
106+
107+
## See also
108+
109+
- [Get started with Azure Cosmos DB for MongoDB and Python](how-to-python-get-started.md)

articles/cosmos-db/mongodb/includes/powershell-set-resource-name.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ ms.service: cosmos-db
44
ms.subservice: mongodb
55
ms.custom: ignite-2022
66
ms.topic: include
7-
ms.date: 06/13/2019
7+
ms.date: 11/14/2022
88
ms.author: diberry
99
---
1010
1. Create a shell variable for *RESOURCE_GROUP_NAME*.
@@ -13,3 +13,9 @@ ms.author: diberry
1313
# Variable for resource group name
1414
$RESOURCE_GROUP_NAME = "msdocs-cosmos"
1515
```
16+
2. Use the [Get-AzCosmosDBAccountKey](/powershell/module/az.cosmosdb/get-azcosmosdbaccountkey) cmdlet to retrieve the name of the first Azure Cosmos DB account in your resource group and store it in the accountName shell variable.
17+
18+
```azurepowershell-interactive
19+
# Get the name of the first Azure Cosmos DB account in your resource group
20+
$ACCOUNT_NAME = (Get-AzCosmosDBAccount -ResourceGroupName $RESOURCE_GROUP_NAME)[0].Name
21+
```

0 commit comments

Comments
 (0)