Übung: Erstellen einer MongoDB-App mit der Azure Cosmos DB für MongoDB
Nun erfahren Sie, wie Sie Azure Cosmos DB for MongoDB-Datenbanken und -Sammlungen programmgesteuert erstellen und einige Daten hinzufügen.
Sie können diese Übung mithilfe einer Sandbox von Microsoft Learn durchführen, die ein temporäres Azure-Abonnement bereitstellt. Zur Aktivierung des Sandbox-Abonnements müssen Sie sich mit einem Microsoft-Konto anmelden. Nach Abschluss dieses Moduls wird das Sandbox-Abonnement automatisch gelöscht. Melden Sie sich nach Aktivierung der Sandbox mit den Anmeldeinformationen für Ihr Sandbox-Abonnement im Azure-Portal an. Stellen Sie sicher, dass Sie sich im Verzeichnis Microsoft Learn Sandbox befinden. Dies wird oben rechts im Portal unter Ihrer Benutzer-ID angezeigt. Falls nicht, klicken Sie auf das Benutzersymbol, und wechseln Sie das Verzeichnis.
Tipp
Wenn Sie möchten, können Sie auch ein eigenes Azure-Abonnement verwenden. Melden Sie sich hierfür mit den Anmeldeinformationen für Ihr Abonnement im Azure-Portal an. Stellen Sie sicher, dass Sie sich im Verzeichnis mit Ihrem Abonnement befinden. Dies wird oben rechts unter Ihrer Benutzer-ID angegeben. Falls nicht, klicken Sie auf das Benutzersymbol, und wechseln Sie das Verzeichnis.
Erstellen einer MongoDB-App mit der Azure Cosmos DB für MongoDB (Node.js)
Erstellen einer MongoDB-App mit der Azure Cosmos DB für MongoDB (Java)
Erstellen einer MongoDB-App mit der Azure Cosmos DB für MongoDB Python
Erstellen einer MongoDB-App mit der Azure Cosmos DB für MongoDB (C#)
In dieser Übung erstellen Sie ein Azure Cosmos DB for MongoDB-Konto, eine Datenbank und eine Sammlung und fügen der Sammlung einige Dokumente hinzu. Sie werden feststellen, dass dieser Code identisch mit dem Code für die Verbindungsherstellung mit einer beliebigen MongoDB-Datenbank ist. Anschließend erstellen Sie eine Sammlung mithilfe von Erweiterungsbefehlen, mit denen Sie den Durchsatz in Anforderungseinheiten pro Sekunde (RU/s) für die Sammlung definieren können.
Vorbereiten Ihrer Entwicklungsumgebung
Wenn Sie das Azure Cosmos DB-Konto und die Umgebung noch nicht vorbereitet haben, mit denen Sie in diesem Lab arbeiten, führen Sie die folgenden Schritte aus. Wechseln Sie andernfalls zum Abschnitt Hinzufügen des Codes zum Erstellen der Datenbanken, Sammlungen und Dokumente für die App.js-Datei.
Wenn Sie die Umgebung und das Azure Cosmos DB-Konto noch nicht vorbereitet haben, mit denen Sie in diesem Lab arbeiten, führen Sie die folgenden Schritte aus. Wechseln Sie andernfalls zum Abschnitt Hinzufügen des Codes zum Erstellen der Datenbanken, Sammlungen und Dokumente für die App.java-Datei.
Wenn Sie das Azure Cosmos DB-Konto und die Umgebung noch nicht vorbereitet haben, mit denen Sie in diesem Lab arbeiten, führen Sie die folgenden Schritte aus. Wechseln Sie andernfalls zum Abschnitt Hinzufügen des Codes zum Erstellen der Datenbanken, Sammlungen und Dokumente für die App.py-Datei.
Wenn Sie die Umgebung und das Azure Cosmos DB-Konto noch nicht vorbereitet haben, mit denen Sie in diesem Lab arbeiten, führen Sie die folgenden Schritte aus. Wechseln Sie andernfalls zum Abschnitt Hinzufügen des Codes zum Erstellen der Datenbanken, Sammlungen und Dokumente für die app.cs-Datei.
Kopieren Sie in Azure Cloud Shell die folgenden Befehle, und fügen Sie sie ein.
git clone https://github.com/MicrosoftLearning/mslearn-cosmosdb.git cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/node/ # Update Azure Cloud Shell node to Version 14.0.0, since the MongoDB driver requires ver 10+ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash source ~/.nvm/nvm.sh nvm install 14.0.0 npm install -g mongodb npm link mongodb # Check if the node version is now v14.0.0 node --version # Create an Azure Cosmos DB for MongoDB account bash ../init.sh
git clone https://github.com/MicrosoftLearning/mslearn-cosmosdb.git cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/java # Download and install the Maven project, this will take a minute or two mvn archetype:generate -DgroupId=com.fabrikam -DartifactId=AzureApp -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false # Replace the projects pom.xml file with the github one that has the MongoDB definition mv pom.xml1 ./AzureApp/pom.xml # Create an Azure Cosmos DB for MongoDB account bash ../init.sh
git clone https://github.com/MicrosoftLearning/mslearn-cosmosdb.git cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/python # Install the MongoDB Python drivers python -m pip install pymongo # Create an Azure Cosmos DB for MongoDB account bash ../init.sh
git clone https://github.com/MicrosoftLearning/mslearn-cosmosdb.git cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/csharp # Add MongoDB driver to DotNet dotnet add package MongoDB.Driver --version 2.16.0 # Create an Azure Cosmos DB for MongoDB account bash ../init.sh
Tipp
Wenn Sie nicht die Sandbox für das Labor verwenden und den Ort angeben möchten, an dem Sie Ihre Datenbank und Speicherobjekte erstellen möchten, fügen Sie dem Aufruf init.sh den Parameter -l LOCATIONNAME hinzu. Wenn Sie eine Ressourcengruppe angeben möchten, fügen Sie außerdem einen Parameter -r YOURRRESOURCEGROUPNAMEHERE dem init.sh Aufruf hinzu.
Hinweis
Dieses Bash-Skript erstellt die Azure Cosmos DB für das MongoDB-Konto. Die Erstellung des Kontos dauert fünf bis zehn Minuten. Sie haben also genügend Zeit, sich eine Tasse Kaffee oder Tee zu holen.
Tipp
Wenn Sie zurückkommen und Ihre Cloudshell zurückgesetzt wurde, führen Sie die folgenden Befehle in der Cloudshell aus, damit Node 14 verwendet wird. Andernfalls funktioniert der Code im nächsten Abschnitt nicht.
- source ~/.nvm/nvm.sh
- nvm install 14.0.0
- npm link mongodb
Wenn die Ausführung der Bash-Datei init.sh abgeschlossen ist, notieren Sie die zurückgegebenen Werte für Verbindungszeichenfolge, Cosmos DB-Kontoname und Name der Ressourcengruppe, da Sie diese im nächsten Abschnitt benötigen. Sie können sich auch den JSON-Code ansehen, der vom Kontoerstellungsskript zurückgegeben wird und sich vor der Verbindungszeichenfolge befindet. In der Mitte des JSON-Codes sollten Sie die Eigenschaft "kind": "MongoDB" sehen.
Hinweis
Sie können die Verbindungszeichenfolge, den Cosmos DB-Kontonamen und den Namen der Ressourcengruppe auch über das Azure-Portal herausfinden.
Hinzufügen des Codes zum Erstellen der Datenbanken, Sammlungen und Dokumente in der Datei „App.js“
Fügen Sie nun den JavaScript-Code zum Erstellen einer Datenbank und einer Sammlung hinzu, und fügen Sie ein Dokument zur Sammlung hinzu.
Hinzufügen des Codes zum Erstellen der Datenbanken, Sammlungen und Dokumente in der Datei „App.java“
Fügen Sie nun den Java-Code zum Erstellen einer Datenbank und einer Sammlung hinzu, und fügen Sie ein Dokument zur Sammlung hinzu.
Hinzufügen des Codes zum Erstellen der Datenbanken, Sammlungen und Dokumente in der Datei „App.py“
Fügen Sie nun den Python-Code zum Erstellen einer Datenbank und einer Sammlung hinzu, und fügen Sie ein Dokument zur Sammlung hinzu.
Hinzufügen des Codes zum Erstellen der Datenbanken, Sammlungen und Dokumente in der Datei „app.cs“
Fügen Sie nun den C#-Code zum Erstellen einer Datenbank und einer Sammlung hinzu, und fügen Sie ein Dokument zur Sammlung hinzu.
Öffnen Sie Azure Cloud Shell, falls nicht bereits geschehen.
Führen Sie den folgenden Befehl aus, um den Code-Editor zu öffnen:
cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/node/ code App.js
cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/java/AzureApp code ./src/main/java/com/fabrikam/App.java
cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/python code App.py
cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/csharp code app.cs
Kopieren Sie den folgenden Code in die App-Datei. Denken Sie daran, den URI-Wert in der Verbindungszeichenfolge zu ersetzen, die Sie im vorherigen Abschnitt kopiert haben.
Dieser Teil des Codes verwendet die MongoDB-Treiber und die Verbindungszeichenfolge für Azure Cosmos DB genau wie eine Verbindungszeichenfolge für jeden beliebigen MongoDB-Server. Der Code definiert und stellt die Verbindung mit dem Azure Cosmos DB-Konto her.
// Uses the MongoDB driver const {MongoClient} = require("mongodb"); async function main() { // One of the values you copied earlier was the connection string, replace it in the following line var url = "TheConnectionStringYouCopiedEarlier"; // define the connection using the MongoClient method ane the url above var mongoClient = new MongoClient(url, function(err,client) { if (err) { console.log("error connecting") } } ); // open the connection await mongoClient.connect();
package com.fabrikam; // Uses the MongoDB driver import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoCollection; import org.bson.Document; import static com.mongodb.client.model.Filters.eq; public class App { public static void main(String[] args) { // One of the values you copied earlier was the connection string, replace it in the following line MongoClientURI uri = new MongoClientURI("TheConnectionStringYouCopiedEarlier"); MongoClient mongoClient = null; try { // define the connection using the MongoClient method ane the url above and open the connection mongoClient = new MongoClient(uri);
# Use the MongoDB drivers import pymongo def main(): # One of the values you copied earlier was the connection string, replace it in the following line uri = "TheConnectionStringYouCopiedEarlier" # We use the "MongoClient" method and the "uri" value to connect to the account client = pymongo.MongoClient(uri) ```
// Uses the MongoDB driver using MongoDB.Driver; using MongoDB.Bson; using System; public class Products { public ObjectId Id { get; set; } public int ProductId { get; set; } public string name { get; set; } } class App { public static void Main (string[] args) { // One of the values you copied earlier was the connection string, replace it in the following line string connectionString = @"TheConnectionStringYouCopiedEarlier"; MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString)); // define the connection using the MongoClient method ane the connectionString above and open the connection var mongoClient = new MongoClient(settings);
Der nächste Schritt stellt eine Verbindung mit der Datenbank products her. Wenn diese Datenbank nicht vorhanden ist, wird sie nur erstellt, wenn in derselben Verbindung oder über Erweiterungsbefehle auch eine Sammlung erstellt wird. Fügen Sie dem Skript im Editor Folgendes hinzu.
// connect to the database "products" var ProductDatabase = mongoClient.db("products");
// connect to the database "products" MongoDatabase ProductDatabase = mongoClient.getDatabase("products");
# connect to the database "products" ProductDatabase = client["products"]
// connect to the database "products" var ProductDatabase = mongoClient.GetDatabase("products");
Als Nächstes stellen Sie eine Verbindung mit der Dokumentensammlung her, sofern diese bereits vorhanden ist, und fügen dann der Sammlung ein Dokument hinzu. Wenn die Sammlung nicht vorhanden ist, erstellt dieser Code diese nur, wenn bei derselben Verbindung auch ein Vorgang für diese Sammlung erfolgt (z. B. das Hinzufügen eines Dokuments zur Sammlung) oder wenn Erweiterungsbefehle verwendet werden. Fügen Sie dem Skript im Editor Folgendes hinzu.
// create a collection "documents" and add one document for "bread" var collection = ProductDatabase.collection('documents'); var insertResult = await collection.insertOne({ ProductId: 1, name: "bread" });
// create a collection "documents" and add one document for "bread" MongoCollection collection = ProductDatabase.getCollection("products"); collection.insertOne(new Document() .append("ProductId", 1) .append("name", "bread"));
# create a collection "products" and add one document for "bread" collection = ProductDatabase["products"] collection.insert_one({ "ProductId": 1, "name": "bread" })
// create a collection "products" and add one document for "bread" var mongoCollection = ProductDatabase.GetCollection<Products>("products"); Products Product = new Products {ProductId=1,name="bread"}; mongoCollection.InsertOne (Product);
Suchen Sie nun nach dem eingefügten Dokument, und zeigen Sie es in der Shell an. Fügen Sie dem Skript im Editor Folgendes hinzu.
// return data where ProductId = 1 const findProduct = await collection.find({ProductId: 1}); await findProduct.forEach(console.log);
// return data where ProductId = 1 Document findProduct = (Document) collection.find(eq("ProductId", 1)).first(); System.out.println(findProduct.toJson()); }
# return data where ProductId = 1 Product_1 = collection.find_one({"ProductId": 1}) print(Product_1)
// return data where ProductId = 1 Products ProductFound = mongoCollection.Find(_ => _.ProductId == 1).FirstOrDefault(); Console.WriteLine ("Id: {0}, ProductId: {1}, name: \'{2}\'", ProductFound.Id, ProductFound.ProductId, ProductFound.name); } }
Beenden Sie nun die Verbindung. Fügen Sie dem Skript im Editor Folgendes hinzu.
// close the connection mongoClient.close(); } main();
// close the connection finally { if (mongoClient != null) { mongoClient.close(); } } } }
# close the connection client.close() if __name__ == '__main__': main()
// Note C# doesn't need to close the connection, it disposes of the connection when the program ends.
Das Skript sollte wie folgt aussehen:
// Uses the MongoDB driver const {MongoClient} = require("mongodb"); async function main() { // One of the values you copied earlier was the connection string, replace it in the following line var url = "TheConnectionStringYouCopiedEarlier"; // define the connection using the MongoClient method ane the url above var mongoClient = new MongoClient(url, function(err,client) { if (err) { console.log("error connecting") } } ); // open the connection await mongoClient.connect(); // connect to the database "products" var ProductDatabase = mongoClient.db("products"); // create a collection "documents" and add one document for "bread" var collection = ProductDatabase.collection('documents'); var insertResult = await collection.insertOne({ ProductId: 1, name: "bread" }); // return data where ProductId = 1 const findProduct = await collection.find({ProductId: 1}); await findProduct.forEach(console.log); // close the connection mongoClient.close(); } main();
package com.fabrikam; // Uses the MongoDB driver import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoCollection; import org.bson.Document; import static com.mongodb.client.model.Filters.eq; public class App { public static void main(String[] args) { // One of the values you copied earlier was the connection string, replace it in the following line MongoClientURI uri = new MongoClientURI("TheConnectionStringYouCopiedEarlier"); MongoClient mongoClient = null; try { // define the connection using the MongoClient method ane the url above and open the connection mongoClient = new MongoClient(uri); // connect to the database "products" MongoDatabase ProductDatabase = mongoClient.getDatabase("products"); // create a collection "products" and add one document for "bread" MongoCollection collection = ProductDatabase.getCollection("products"); collection.insertOne(new Document() .append("ProductId", 1) .append("name", "bread")); // return data where ProductId = 1 Document findProduct = (Document) collection.find(eq("ProductId", 1)).first(); System.out.println(findProduct.toJson()); } // close the connection finally { if (mongoClient != null) { mongoClient.close(); } } } }
# Use the MongoDB drivers import pymongo def main(): # One of the values you copied earlier was the connection string, replace it in the following line uri = "TheConnectionStringYouCopiedEarlier" # We use the "MongoClient" method and the "uri" value to connect to the account client = pymongo.MongoClient(uri) # connect to the database "products" ProductDatabase = client["products"] # create a collection "products" and add one document for "bread" collection = ProductDatabase["products"] collection.insert_one({ "ProductId": 1, "name": "bread" }) # return data where ProductId = 1 Product_1 = collection.find_one({"ProductId": 1}) print(Product_1) # close the connection client.close() if __name__ == '__main__': main()
// Uses the MongoDB driver using MongoDB.Driver; using MongoDB.Bson; using System; public class Products { public ObjectId Id { get; set; } public int ProductId { get; set; } public string name { get; set; } } class App { public static void Main (string[] args) { // One of the values you copied earlier was the connection string, replace it in the following line string connectionString = @"TheConnectionStringYouCopiedEarlier"; MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString)); // define the connection using the MongoClient method ane the connectionString above and open the connection var mongoClient = new MongoClient(settings); // connect to the database "products" var ProductDatabase = mongoClient.GetDatabase("products"); // create a collection "products" and add one document for "bread" var mongoCollection = ProductDatabase.GetCollection<Products>("products"); Products Product = new Products {ProductId=1,name="bread"}; mongoCollection.InsertOne (Product); // return data where ProductId = 1 Products ProductFound = mongoCollection.Find(_ => _.ProductId == 1).FirstOrDefault(); Console.WriteLine ("Id: {0}, ProductId: {1}, name: \'{2}\'", ProductFound.Id, ProductFound.ProductId, ProductFound.name); } }
Fahren Sie fort, und speichern Sie das Programm. Wählen Sie oben rechts im Code-Editor die Option Speichern aus, oder drücken Sie STRG+S. Wählen Sie nun Editor schließen aus, oder drücken Sie STRG+Q, um zur Shell zurückzukehren.
Führen Sie nun die App mit dem folgenden Befehl aus.
node App.js
mvn clean compile exec:java
python App.py
dotnet run
Dieses Skript sollte ein ähnliches Ergebnis wie das folgende zurückgeben. Das bedeutet, dass Sie die Datenbank und die Sammlung erstellt und dieser ein Dokument hinzugefügt haben.
{ _id: new ObjectId("62aed08663c0fd62d30240db"), ProductId: 1, name: 'bread' }
INFO: Opened connection [connectionId{localValue:3, serverValue:74678510}] to learn-account-cosmos-665601-westus.mongo.cosmos.azure.com:10255 { "_id" : { "$oid" : "62afa8c3dff473012e7b7910" }, "ProductId" : 1, "name" : "bread" } Jun 19, 2022 10:52:59 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:3, serverValue:74678510}] to learn-account-cosmos-665601-westus.mongo.cosmos.azure.com:10255 because the pool has been closed.
{'_id': ObjectId('62afecc3a04e32b92451ac5d'), 'ProductId': 1, 'name': 'bread'}
Id: 62affed8147b5206db146298, ProductId: 1, name: 'bread'
Sie werden bemerken, dass dieser Code mit dem Code identisch ist, den Sie ausführen, um eine Datenbank, eine Sammlung oder ein Dokument in einer MongoDB-Datenbank zu erstellen. Daher sollten Sie keine Schwierigkeiten mit der Programmierung für die Azure Cosmos DB für MongoDB haben, wenn Sie sich bereits mit dem Erstellen von Apps auskennen, die eine Verbindung mit MongoDB herstellen.
Verwaltete Identitäten
Für Produktionsworkloads wird die Verwendung von verwalteten Identitäten zur Authentifizierung bei Azure Cosmos DB empfohlen. Auf diese Weise müssen Sie die Verbindungszeichenfolge nicht in Ihrem Code speichern. Im nächsten Abschnitt verwenden Sie verwaltete Identitäten, um sich bei Azure Cosmos DB zu authentifizieren.
In einer Produktionsumgebung sollten Sie eine verwaltete Identität mit möglichst geringen Berechtigungen verwenden. Sie können eine oder mehrere benutzerseitig zugewiesene verwaltete Identitäten erstellen und sie dem Azure Cosmos DB-Konto zuweisen. Für dieses Lab erstellen Sie eine systemseitig zugewiesene verwaltete Identität für das Azure Cosmos DB-Konto.
- Navigieren Sie im Azure-Portal zu dem Azure Cosmos DB-Konto, das Sie zuvor erstellt haben.
- Wählen Sie im linken Menü unter Einstellungen die Option Identität aus.
- Wählen Sie im Bereich Identität die Option Systemseitig zugewiesen aus.
- Wählen Sie für den Status die Option Ein aus.
- Wählen Sie Speichern.
- Es dauert einige Minuten, bis die verwaltete Identität erstellt wird.
Nachdem die verwaltete Identität erstellt wurde, müssen Sie ihr die erforderlichen Berechtigungen für das Azure Cosmos DB-Konto zuweisen. Verwenden Sie RBAC (rollenbasierte Zugriffssteuerung), um der verwalteten Identität die erforderlichen Berechtigungen zuzuweisen. In diesem Lab weisen Sie der verwalteten Identität die Rolle Mitwirkender zu, damit sie Daten im Azure Cosmos DB-Konto lesen und schreiben kann. In einer Produktionsumgebung sollten Sie die Rolle mit den geringsten Berechtigungen zuweisen.
- Navigieren Sie im Azure-Portal zu dem Azure Cosmos DB-Konto, das Sie zuvor erstellt haben.
- Wählen Sie im linken Menü unter Einstellungen die Option Zugriffssteuerung (IAM) aus.
- Wählen Sie + Hinzufügen und dann Rollenzuweisung hinzufügen aus.
- Wählen Sie unter der privilegierten Administratorrolle zunächst Mitwirkender und dann Weiter aus.
- Wählen Sie unter Mitglieder zunächst Verwaltete Identität und dann + Mitglieder auswählen aus.
- Suchen Sie im Bereich Verwaltete Identitäten auswählen nach der zuvor erstellten verwalteten Identität, wählen Sie sie aus, und wählen Sie dann Überprüfen + Zuweisen aus.
Sie verfügen nun über eine verwaltete Identität mit den erforderlichen Berechtigungen, die dem Azure Cosmos DB-Konto zugewiesen ist. Nun verwenden Sie die verwaltete Identität, um sich beim Azure Cosmos DB-Konto zu authentifizieren.
Verwenden von Erweiterungsbefehlen zum Verwalten von gespeicherten Daten in der Azure Cosmos DB-API für MongoDB
Obwohl der obige Code identisch mit der Verbindungsherstellung mit einem MongoDB-Server und der anschließenden Verbindung mit dem Azure Cosmos DB for MongoDB-Konto ist, werden möglicherweise nicht alle Azure Cosmos DB-Features genutzt. Das bedeutet, dass die Standardtreibermethoden zum Erstellen der Sammlungen auch die Standardparameter des Azure Cosmos DB-Kontos verwenden, um diese Sammlungen zu erstellen. Daher können Sie mithilfe dieser Methoden keine Erstellungsparameter wie Durchsatz-, Shardschlüssel- oder Autoskalierungseinstellungen definieren.
Mit der Azure Cosmos DB-API für MongoDB können Sie von den Vorteile von Cosmos DB profitieren. Zu diesen Vorteilen gehören globale Verteilung, automatisches Sharding, Hochverfügbarkeit, Latenzgarantien, automatische Verschlüsselung im Ruhezustand, Sicherungen u. v. m. Darüber hinaus können Sie Ihre Investitionen in die MongoDB-App weiter nutzen. Sie können mit der API für MongoDB von Azure Cosmos DB über einen der Open-Source-MongoDB-Clienttreiber kommunizieren. Die Azure Cosmos DB-API für MongoDB ermöglicht die Verwendung vorhandener Clienttreiber durch Nutzung des Wire Protocol von MongoDB.
Schreiben Sie Code, mit dem eine Sammlung erstellt wird, und definieren Sie den Shardschlüssel und den Durchsatz.
Öffnen Sie Azure Cloud Shell, falls nicht bereits geschehen.
Führen Sie den folgenden Befehl aus, um den Code-Editor zu öffnen:
cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/node code App.js
cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/java/AzureApp code ./src/main/java/com/fabrikam/App.java
cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/python code App.py
cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/csharp code app.cs
Kopieren Sie den folgenden Code in die Datei .
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity"; const { MongoClient, ObjectId } = require('mongodb'); import axios from "axios"; async function main() { // Environment variables const endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT; const listConnectionStringUrl = process.env.AZURE_COSMOS_LISTCONNECTIONSTRINGURL; const scope = process.env.AZURE_COSMOS_SCOPE; // For system-assigned managed identity. const credential = new DefaultAzureCredential(); // Acquire the access token const accessToken = await credential.getToken(scope); // Get the connection string const config = { method: 'post', url: listConnectionStringUrl, headers: { 'Authorization': 'Bearer ${accessToken.token}' } }; const response = await axios(config); const keysDict = response.data; const connectionString = keysDict['connectionStrings'][0]['connectionString']; // Connect to Azure Cosmos DB for MongoDB const mongoClient = new MongoClient(connectionString); // open the connection await mongoClient.connect();
package com.fabrikam; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import javax.net.ssl.*; import java.net.InetSocketAddress; import com.azure.identity.*; import com.azure.core.credential.*; import java.net.http.*; import java.net.URI; public class App { public static void main(String[] args) { // Environment variables String endpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT"); String listConnectionStringUrl = System.getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL"); String scope = System.getenv("AZURE_COSMOS_SCOPE"); // For system-assigned managed identity. DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build(); MongoClient mongoClient = null; try { // Acquire the access token AccessToken accessToken = defaultCredential .getToken(new TokenRequestContext().addScopes(scope)) .block(); String token = accessToken.getToken(); // Retrieve the connection string HttpClient client = HttpClient.newBuilder().build(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI(listConnectionStringUrl)) .header("Authorization", "Bearer " + token) .POST(HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); JSONParser parser = new JSONParser(); JSONObject responseBody = parser.parse(response.body()); List<Map<String, String>> connectionStrings = responseBody.get("connectionStrings"); String connectionString = connectionStrings.get(0).get("connectionString"); // Connect to Azure Cosmos DB for MongoDB MongoClientURI uri = new MongoClientURI(connectionString); mongoClient = new MongoClient(uri);
import os import pymongo import requests from azure.identity import ManagedIdentityCredential, ClientSecretCredential def main(): # Environment variables endpoint = os.getenv('AZURE_COSMOS_RESOURCEENDPOINT') listConnectionStringUrl = os.getenv('AZURE_COSMOS_LISTCONNECTIONSTRINGURL') scope = os.getenv('AZURE_COSMOS_SCOPE') # For system-assigned managed identity cred = ManagedIdentityCredential() # Get the connection string session = requests.Session() token = cred.get_token(scope) response = session.post(listConnectionStringUrl, headers={"Authorization": "Bearer {}".format(token.token)}) keys_dict = response.json() conn_str = keys_dict["connectionStrings"][0]["connectionString"] # Connect to Azure Cosmos DB for MongoDB client = pymongo.MongoClient(conn_str)
using MongoDB.Driver; using Azure.Identity; using Azure.Core; using System; using System.Net.Http; using System.Text.Json; using System.Collections.Generic; using System.Threading.Tasks; public class Products { public int ProductId { get; set; } public string name { get; set; } } class App { public static async Task Main(string[] args) { // Environment variables var endpoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT"); var listConnectionStringUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTCONNECTIONSTRINGURL"); var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE"); // For system-assigned identity. var tokenProvider = new DefaultAzureCredential(); // Acquire the access token. AccessToken accessToken = await tokenProvider.GetTokenAsync( new TokenRequestContext(scopes: new[] { scope })); // Get the connection string. using var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}"); var response = await httpClient.PostAsync(listConnectionStringUrl, null); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); // Parse the connection string. var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody); string connectionString = connectionStrings["connectionStrings"][0]["connectionString"]; // Initialize the MongoClient with the connection string. var mongoClient = new MongoClient(connectionString);
Der nächste Schritt stellt eine Verbindung mit der Datenbank employees her. Wenn diese Datenbank nicht vorhanden ist, wird sie nur erstellt, wenn in derselben Verbindung oder über Erweiterungsbefehle auch eine Sammlung erstellt wird. Fügen Sie dem Skript im Editor Folgendes hinzu.
// connect to the database "HumanResources" var EmployeeDatabase = mongoClient.db("HumanResources");
// connect to the database "HumanResources" MongoDatabase EmployeeDatabase = mongoClient.getDatabase("HumanResources");
# connect to the database "HumanResources" EmployeeDatabase = client["HumanResources"]
// connect to the database "HumanResources" var EmployeeDatabase = mongoClient.GetDatabase("HumanResources");
Bisher ähnelt dieser Code dem Code aus dem vorherigen Abschnitt. In diesem Schritt nutzen Sie die Erweiterungsbefehle und erstellen eine benutzerdefinierte Aktion. Mit dieser Aktion können Sie den Durchsatz und den Shardschlüssel der Sammlung definieren. Der Schritt stellt wiederum die Parameter für Azure Cosmos DB bereit, die beim Erstellen der Sammlung verwendet werden sollen. Fügen Sie dem Skript im Editor Folgendes hinzu.
// create the Employee collection with a throughput of 1000 RUs and with EmployeeId as the sharding key var result = EmployeeDatabase.command({customAction: "CreateCollection", collection: "Employee", offerThroughput: 1000, shardKey: "EmployeeId"});
// create the Employee collection with a throughput of 1000 RUs and with EmployeeId as the sharding key Document employeeCollectionDef = new Document(); employeeCollectionDef.append("customAction", "CreateCollection"); employeeCollectionDef.append("collection", "Employee"); employeeCollectionDef.append("offerThroughput", 1000); employeeCollectionDef.append("shardKey", "EmployeeId"); Document result = EmployeeDatabase.runCommand(employeeCollectionDef);
# create the Employee collection with a throughput of 1000 RUs and with EmployeeId as the sharding key EmployeeDatabase.command({'customAction': "CreateCollection", 'collection': "Employee", 'offerThroughput': 1000, 'shardKey': "EmployeeId"})
// create the Employee collection with a throughput of 1000 RUs and with EmployeeId as the sharding key var result = EmployeeDatabase.RunCommand<BsonDocument>(@"{customAction: ""CreateCollection"", collection: ""Employee"", offerThroughput: 1000, shardKey: ""EmployeeId""}");
Der Rest ist identisch mit dem vorherigen Beispiel. Sie stellen eine Verbindung mit der Sammlung her, fügen einige Zeilen ein und geben schließlich eine Zeile zurück. Fügen Sie dem Skript im Editor Folgendes hinzu.
// Connect to the collection "Employee" and add two documents for "Marcos" and "Tam" var collection = EmployeeDatabase.collection('Employee'); var insertResult = await collection.insertOne({EmployeeId: 1, email: "Marcos@fabrikam.com", name: "Marcos"}); insertResult = await collection.insertOne({EmployeeId: 2, email: "Tam@fabrikam.com", name: "Tam"}); // return data where ProductId = 1 const findProduct = await collection.find({EmployeeId: 1}); await findProduct.forEach(console.log); // close the connection mongoClient.close(); } main();
// Connect to the collection "Employee" and add two documents for "Marcos" and "Tam" MongoCollection collection = EmployeeDatabase.getCollection("Employee"); collection.insertOne(new Document() .append("EmployeeId", 1) .append("email","Marcos@fabrikam.com") .append("name", "Marcos")); collection.insertOne(new Document() .append("EmployeeId", 2) .append("email","Tam@fabrikam.com") .append("name", "Tam")); // return data where EmployeeId = 1 Document findEmployee = (Document) collection.find(eq("EmployeeId", 1)).first(); System.out.println(findEmployee.toJson()); } // close the connection finally { if (mongoClient != null) { mongoClient.close(); } } } }
# Connect to the collection "Employee" and add two documents for "Marcos" and "Tam" collection = EmployeeDatabase["Employee"] collection.insert_one({ "EmployeeId": 1, "email": "Marcos@fabrikan.com", "name": "Marcos" }) collection.insert_one({ "EmployeeId": 2, "email": "Tam@fabrikan.com", "name": "Tam" }) # return data where ProductId = 1 Product_1 = collection.find_one({"EmployeeId": 1}) print(Product_1) # close the connection client.close() if __name__ == '__main__': main()
// Connect to the collection "Employee" and add two documents for "Marcos" and "Tam" var mongoCollection = EmployeeDatabase.GetCollection<Employees>("Employee"); Employees Employee = new Employees {EmployeeId=1,email="Marcos@fabrikam.com",name="Marcos"}; mongoCollection.InsertOne (Employee); Employee = new Employees {EmployeeId=2,email="Tam@fabrikam.com",name="Tam"}; mongoCollection.InsertOne (Employee); // return data where EmployeeId = 1 Employees EmployeeFound = mongoCollection.Find(_ => _.EmployeeId == 1).FirstOrDefault(); Console.WriteLine ("Id: {0}, EmployeeId: {1}, email: \'{2}\', name: \'{3}\'", EmployeeFound.Id, EmployeeFound.EmployeeId, EmployeeFound.email, EmployeeFound.name); } }
Das Skript sollte wie folgt aussehen:
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity"; const { MongoClient, ObjectId } = require('mongodb'); import axios from "axios"; async function main() { // Environment variables const endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT; const listConnectionStringUrl = process.env.AZURE_COSMOS_LISTCONNECTIONSTRINGURL; const scope = process.env.AZURE_COSMOS_SCOPE; // For system-assigned managed identity. const credential = new DefaultAzureCredential(); // Acquire the access token const accessToken = await credential.getToken(scope); // Get the connection string const config = { method: 'post', url: listConnectionStringUrl, headers: { 'Authorization': 'Bearer ${accessToken.token}' } }; const response = await axios(config); const keysDict = response.data; const connectionString = keysDict['connectionStrings'][0]['connectionString']; // Connect to Azure Cosmos DB for MongoDB const mongoClient = new MongoClient(connectionString); // open the connection await mongoClient.connect(); // connect to the database "HumanResources" var EmployeeDatabase = mongoClient.db("HumanResources"); // create the Employee collection with a throughput of 1000 RUs and with EmployeeId as the sharding key var result = EmployeeDatabase.command({customAction: "CreateCollection", collection: "Employee", offerThroughput: 1000, shardKey: "EmployeeId"}); // Connect to the collection "Employee" and add two documents for "Marcos" and "Tam" var collection = EmployeeDatabase.collection('Employee'); var insertResult = await collection.insertOne({EmployeeId: 1, email: "Marcos@fabrikam.com", name: "Marcos"}); insertResult = await collection.insertOne({EmployeeId: 2, email: "Tam@fabrikam.com", name: "Tam"}); // return data where ProductId = 1 const findProduct = await collection.find({EmployeeId: 1}); await findProduct.forEach(console.log); // close the connection mongoClient.close(); } main();
package com.fabrikam; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import javax.net.ssl.*; import java.net.InetSocketAddress; import com.azure.identity.*; import com.azure.core.credential.*; import java.net.http.*; import java.net.URI; public class App { public static void main(String[] args) { // Environment variables String endpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT"); String listConnectionStringUrl = System.getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL"); String scope = System.getenv("AZURE_COSMOS_SCOPE"); // For system-assigned managed identity. DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build(); MongoClient mongoClient = null; try { // Acquire the access token AccessToken accessToken = defaultCredential .getToken(new TokenRequestContext().addScopes(scope)) .block(); String token = accessToken.getToken(); // Retrieve the connection string HttpClient client = HttpClient.newBuilder().build(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI(listConnectionStringUrl)) .header("Authorization", "Bearer " + token) .POST(HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); JSONParser parser = new JSONParser(); JSONObject responseBody = parser.parse(response.body()); List<Map<String, String>> connectionStrings = responseBody.get("connectionStrings"); String connectionString = connectionStrings.get(0).get("connectionString"); // Connect to Azure Cosmos DB for MongoDB MongoClientURI uri = new MongoClientURI(connectionString); mongoClient = new MongoClient(uri); // connect to the database "HumanResources" MongoDatabase EmployeeDatabase = mongoClient.getDatabase("HumanResources"); // create the Employee collection with a throughput of 1000 RUs and with EmployeeId as the sharding key Document employeeCollectionDef = new Document(); employeeCollectionDef.append("customAction", "CreateCollection"); employeeCollectionDef.append("collection", "Employee"); employeeCollectionDef.append("offerThroughput", 1000); employeeCollectionDef.append("shardKey", "EmployeeId"); Document result = EmployeeDatabase.runCommand(employeeCollectionDef); // Connect to the collection "Employee" and add two documents for "Marcos" and "Tam" MongoCollection collection = EmployeeDatabase.getCollection("Employee"); collection.insertOne(new Document() .append("EmployeeId", 1) .append("email","Marcos@fabrikam.com") .append("name", "Marcos")); collection.insertOne(new Document() .append("EmployeeId", 2) .append("email","Tam@fabrikam.com") .append("name", "Tam")); // return data where EmployeeId = 1 Document findEmployee = (Document) collection.find(eq("EmployeeId", 1)).first(); System.out.println(findEmployee.toJson()); } // close the connection finally { if (mongoClient != null) { mongoClient.close(); } } } }
import os import pymongo import requests from azure.identity import ManagedIdentityCredential, ClientSecretCredential def main(): # Environment variables endpoint = os.getenv('AZURE_COSMOS_RESOURCEENDPOINT') listConnectionStringUrl = os.getenv('AZURE_COSMOS_LISTCONNECTIONSTRINGURL') scope = os.getenv('AZURE_COSMOS_SCOPE') # For system-assigned managed identity cred = ManagedIdentityCredential() # Get the connection string session = requests.Session() token = cred.get_token(scope) response = session.post(listConnectionStringUrl, headers={"Authorization": "Bearer {}".format(token.token)}) keys_dict = response.json() conn_str = keys_dict["connectionStrings"][0]["connectionString"] # Connect to Azure Cosmos DB for MongoDB client = pymongo.MongoClient(conn_str) # connect to the database "HumanResources" EmployeeDatabase = client["HumanResources"] # create the Employee collection with a throughput of 1000 RUs and with EmployeeId as the sharding key EmployeeDatabase.command({'customAction': "CreateCollection", 'collection': "Employee", 'offerThroughput': 1000, 'shardKey': "EmployeeId"}) # Connect to the collection "Employee" and add two documents for "Marcos" and "Tam" collection = EmployeeDatabase["Employee"] collection.insert_one({ "EmployeeId": 1, "email": "Marcos@fabrikan.com", "name": "Marcos" }) collection.insert_one({ "EmployeeId": 2, "email": "Tam@fabrikan.com", "name": "Tam" }) # return data where ProductId = 1 Product_1 = collection.find_one({"EmployeeId": 1}) print(Product_1) # close the connection client.close() if __name__ == '__main__': main()
using MongoDB.Driver; using Azure.Identity; using Azure.Core; using System; using System.Net.Http; using System.Text.Json; using System.Collections.Generic; using System.Threading.Tasks; public class Products { public int ProductId { get; set; } public string name { get; set; } } class App { public static async Task Main(string[] args) { // Environment variables var endpoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT"); var listConnectionStringUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTCONNECTIONSTRINGURL"); var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE"); // For system-assigned identity. var tokenProvider = new DefaultAzureCredential(); // Acquire the access token. AccessToken accessToken = await tokenProvider.GetTokenAsync( new TokenRequestContext(scopes: new[] { scope })); // Get the connection string. using var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}"); var response = await httpClient.PostAsync(listConnectionStringUrl, null); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); // Parse the connection string. var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody); string connectionString = connectionStrings["connectionStrings"][0]["connectionString"]; // Initialize the MongoClient with the connection string. var mongoClient = new MongoClient(connectionString); // connect to the database "HumanResources" var EmployeeDatabase = mongoClient.GetDatabase("HumanResources"); // create the Employee collection with a throughput of 1000 RUs and with EmployeeId as the sharding key var result = EmployeeDatabase.RunCommand<BsonDocument>(@"{customAction: ""CreateCollection"", collection: ""Employee"", offerThroughput: 1000, shardKey: ""EmployeeId""}"); // Connect to the collection "Employee" and add two documents for "Marcos" and "Tam" var mongoCollection = EmployeeDatabase.GetCollection<Employees>("Employee"); Employees Employee = new Employees {EmployeeId=1,email="Marcos@fabrikam.com",name="Marcos"}; mongoCollection.InsertOne (Employee); Employee = new Employees {EmployeeId=2,email="Tam@fabrikam.com",name="Tam"}; mongoCollection.InsertOne (Employee); // return data where EmployeeId = 1 Employees EmployeeFound = mongoCollection.Find(_ => _.EmployeeId == 1).FirstOrDefault(); Console.WriteLine ("Id: {0}, EmployeeId: {1}, email: \'{2}\', name: \'{3}\'", EmployeeFound.Id, EmployeeFound.EmployeeId, EmployeeFound.email, EmployeeFound.name); } }
Fahren Sie fort, und speichern Sie das Programm. Wählen Sie oben rechts im Code-Editor die Option Speichern aus, oder drücken Sie STRG+S. Wählen Sie nun Editor schließen aus, oder drücken Sie STRG+Q, um zur Shell zurückzukehren.
Führen Sie nun die App mit dem folgenden Befehl aus.
node App.js
mvn clean compile exec:java
python App.py
dotnet run
Das zurückgegebene Ergebnis sollte dem unten stehenden ähneln. Das bedeutet, dass Sie die Datenbank und die Sammlung erstellt und dieser ein Dokument hinzugefügt haben.
{ _id: new ObjectId("62aed08663c0fd62d30240db"), EmployeeId: 1, email: 'Marcos@fabrikam.com' name: 'Marcos' }
INFO: Opened connection [connectionId{localValue:3, serverValue:2080122971}] to learn-account-cosmos-845083734-westus.mongo.cosmos.azure.com:10255 { "_id" : { "$oid" : "62afd8e2c471f3011bd415fe" }, "EmployeeId" : 1, "email" : "Marcos@fabrikam.com", "name" : "Marcos" } Jun 20, 2022 2:18:11 AM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:3, serverValue:2080122971}] to learn-account-cosmos-845083734-westus.mongo.cosmos.azure.com:10255 because the pool has been closed.
{'_id': ObjectId('62afecc3a04e32b92451ac5d'), 'EmployeeId': 1, 'email': 'Marcos@fabrikan.com', 'name': 'Marcos'}
Id: 62affed8147b5206db146298, EmployeeId: 1, email: 'Marcos@fabrikam.com', name: 'Marcos'
Dieses letzte Resultset hat jedoch nur bestätigt, dass eine Datenbank, eine Sammlung und Dokumente erstellt wurden. Doch wurden auch der Shardschlüssel und der Durchsatz geändert? Führen Sie in Cloud Shell die folgenden Befehle aus, um sich zu vergewissern, dass die Änderungen wirksam sind.
Vergewissern Sie sich, dass der Shardschlüssel in EmployeeId (Standardwert: id) geändert wurde. Denken Sie daran, den Namen der Ressourcengruppe und den Kontonamen durch die Namen zu ersetzen, die Sie sich zu Beginn des Labs notiert haben.
az cosmosdb mongodb collection show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734
Das Ergebnis sollte die Eigenschaft "shardKey": {"EmployeeId": "Hash"} enthalten.
Vergewissern Sie sich, dass der Durchsatz in 1000 (Standardwert: 400) geändert wurde. Denken Sie daran, den Namen der Ressourcengruppe und den Kontonamen durch die Namen zu ersetzen, die Sie sich zu Beginn des Labs notiert haben.
az cosmosdb mongodb collection throughput show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734
Das Ergebnis sollte die Eigenschaft "throughput": 1000 enthalten.
Dieser Code veranschaulicht die Möglichkeiten, die sich durch die Verwendung von Erweiterungsbefehlen im Code ergeben, unter anderem die Definition von Azure Cosmos DB-Erstellungsparametern. Auf diese Weise können Sie steuern, wie Sammlungen von Azure Cosmos DB erstellt und verarbeitet werden.
Fahren Sie mit der Wissensbeurteilung zu diesem Modul fort, nachdem Sie diese Übung absolviert haben.