Oefening: een MongoDB DB-app maken met behulp van De Azure Cosmos DB voor MongoDB
Het is tijd om programmatisch te bekijken hoe u onze Azure Cosmos DB voor MongoDB-databases, -verzamelingen en enkele gegevens kunt maken.
Deze oefening kan worden voltooid met behulp van een Microsoft Learn-sandbox, die een tijdelijk Azure-abonnement biedt. Als u het sandbox-abonnement wilt activeren, moet u zich aanmelden met een Microsoft-account. Het sandbox-abonnement wordt automatisch verwijderd wanneer u deze module voltooit. Nadat de sandbox is geactiveerd, meldt u zich aan bij Azure Portal met behulp van de referenties voor uw sandbox-abonnement. Zorg ervoor dat u in de map Microsoft Learn Sandbox werkt, die wordt aangegeven in de rechterbovenhoek van de portal onder uw gebruikers-ID. Als dat niet het is, selecteert u het gebruikerspictogram en schakelt u over naar een andere map.
Aanbeveling
Als u wilt, kunt u uw eigen Azure-abonnement gebruiken. Meld u hiervoor aan bij Azure Portal met behulp van referenties voor uw abonnement. Zorg ervoor dat u in de map met uw abonnement werkt, die rechtsboven onder uw gebruikers-id wordt aangegeven. Als dat niet het is, selecteert u het gebruikerspictogram en schakelt u over naar een andere map.
Maak een MongoDB-app met Azure Cosmos DB voor MongoDB Node.js
Een MongoDB-app maken met java Azure Cosmos DB voor MongoDB
Een MongoDB-app maken met behulp van Python Azure Cosmos DB voor MongoDB
Een MongoDB-app maken met C# Azure Cosmos DB voor MongoDB
In deze oefening maakt u een Azure Cosmos DB voor MongoDB-account, een database, een verzameling en voegt u een aantal documenten toe aan de verzameling. U ziet dat deze code identiek is aan de manier waarop u verbinding maakt met een MongoDB-database. Vervolgens maakt u een verzameling met behulp van extensieopdrachten waarmee u de doorvoer in aanvraageenheden per seconde (RU's) voor de verzameling kunt definiëren.
Uw ontwikkelomgeving voorbereiden
Als u niet beschikt over het Azure Cosmos DB-account en de omgeving waar u aan dit lab werkt, volgt u deze stappen om dit te doen. Anders gaat u naar de sectie Voeg de code toe om de databases, collectie en document te maken aan het App.js-bestand.
Als u niet de omgeving en het Azure Cosmos DB-account waar u aan dit lab werkt, volgt u deze stappen om dit te doen. Anders gaat u naar de sectie Voeg de code voor het maken van de databases, collection en document toe aan het bestand App.java.
Als u niet het Azure Cosmos DB-account en de omgeving waar u aan dit lab werkt, volgt u deze stappen om dit te doen. Ga anders naar de sectie De code toevoegen om de databases, collectie en document in het App.py-bestand te maken.
Als u niet beschikt over de omgeving en het Azure Cosmos DB-account waar u aan dit lab werkt, volgt u deze stappen om dit te doen. Anders ga naar de sectie code toevoegen aan het app.cs-bestand om de databases, collectie en document te maken.
Kopieer en plak de volgende opdrachten in Azure Cloud Shell.
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.shgit 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.shgit 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.shgit 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.shAanbeveling
Als u de sandbox voor het lab niet gebruikt en u de locatie wilt opgeven waar u uw database- en opslagobjecten wilt maken, voegt u een PARAMETER -l LOCATIONNAME toe aan de init.sh-aanroep . Als u bovendien een resourcegroep wilt opgeven, voegt u een parameter -r YOURRRESOURCEGROUPNAMEHERE toe aan de init.sh aanroep.
Notitie
Met dit bash-script wordt het Azure Cosmos DB voor MongoDB-account gemaakt. Het kan 5-10 minuten duren om dit account te maken , dus het kan een goed moment zijn om een kopje koffie of thee te krijgen.
Aanbeveling
Als u terugkomt en de cloudshell opnieuw is ingesteld, voert u de volgende opdrachten uit in de cloudshell om Node versie 14 te gebruiken, anders mislukt de code in de volgende sectie.
- bron ~/.nvm/nvm.sh
- nvm install 14.0.0
- npm link mongodb
Wanneer het bash-init.sh-bestand is voltooid, kopieer de verbindingsreeks, de naam van het Cosmos DB-account en de naam van de resourcegroep die zijn geretourneerd. We hebben ze nodig in de volgende sectie. U kunt ook de JSON controleren die wordt geretourneerd door het script voor het maken van het account dat zich vóór de verbindingsreeks bevindt. Als u ergens in het midden van de JSON kijkt, ziet u de eigenschap 'soort': 'MongoDB'.
Notitie
Houd er rekening mee dat de verbindingsreeks, de naam van het Cosmos DB-account en de naam van de resourcegroep ook kunnen worden gevonden met behulp van Azure Portal.
Voeg de code toe om de databases, verzameling en documenten te maken aan het App.js-bestand
Het is nu tijd om onze JavaScript-code toe te voegen om een database, een verzameling te maken en een document toe te voegen aan de verzameling.
Voeg de code toe om de databases, verzameling en documenten te maken aan het App.java-bestand
Het is nu tijd om onze Java-code toe te voegen om een database, een verzameling te maken en een document toe te voegen aan de verzameling.
Voeg de code toe om de databases, verzameling en documenten te maken aan het App.py-bestand
Het is nu tijd om onze Python-code toe te voegen om een database, een verzameling te maken en een document toe te voegen aan de verzameling.
Voeg de code toe om de databases, verzameling en documenten te maken aan het app.cs-bestand
Het is nu tijd om onze C#-code toe te voegen om een database, een verzameling te maken en een document toe te voegen aan de verzameling.
Open de Azure Cloud Shell in nog niet geopend.
Voer de volgende opdracht uit om de code-editor te openen.
cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/node/ code App.jscd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/java/AzureApp code ./src/main/java/com/fabrikam/App.javacd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/python code App.pycd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/csharp code app.csKopieer de volgende code naar het app-bestand. Vergeet niet dat u de URI-waarde moet vervangen voor de verbindingsreeks die u in de vorige sectie hebt gekopieerd.
Dit deel van de code maakt gebruik van de MongoDB-stuurprogramma's en gebruikt de verbindingsreeks naar Azure Cosmos DB, zoals u normaal gesproken een verbindingsreeks op een MongoDB-server zou gebruiken. De code definieert en opent vervolgens de verbinding met het Azure Cosmos DB-account.
// 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);De volgende stap maakt verbinding met de productendatabase . Als deze database niet bestaat, wordt deze alleen gemaakt als er ook een verzameling in dezelfde verbinding wordt gemaakt of met behulp van extensieopdrachten. Voeg het volgende toe aan het script in de editor.
// 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");Vervolgens maken we verbinding met de documentenverzameling als deze al bestaat en voegt u vervolgens één document toe aan de verzameling. Als de verzameling niet bestaat, wordt met deze code de verzameling gemaakt als deze ook een bewerking uitvoert op die verzameling in dezelfde verbinding (bijvoorbeeld een document toevoegen aan de verzameling) of met behulp van extensieopdrachten. Voeg het volgende toe aan het script in de editor.
// 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);Hiermee kunt u nu zoeken naar het ingevoegde document en dit weergeven in de shell. Voeg het volgende toe aan het script in de editor.
// 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); } }Ten slotte gaan we de verbinding sluiten. Voeg het volgende toe aan het script in de editor.
// 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.Het script moet er als volgt uitzien:
// 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); } }Laten we het programma opslaan. Selecteer in de rechterbovenhoek van de code-editor en selecteer Opslaan (of Ctrl+S). Selecteer nu Sluit Editor (of Ctrl+Q) om terug te gaan naar de Shell.
Nu gaan we de app uitvoeren met de volgende opdracht.
node App.jsmvn clean compile exec:javapython App.pydotnet runDit script moet een vergelijkbaar resultaat retourneren als het volgende. Dit betekent dat we de database, verzameling en er een document aan hebben toegevoegd.
{ _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'
Zoals u ziet, is deze code dezelfde code die u zou uitvoeren om een database, verzameling en document op een MongoDB-database te maken. Programmeren voor Azure Cosmos DB voor MongoDB moet dus transparant zijn als u al bekend bent met het maken van apps die verbinding maken met MongoDB.
Beheerde identiteiten
Voor productieworkloads raden we u aan beheerde identiteiten te gebruiken om te verifiëren bij Azure Cosmos DB. Op deze manier hoeft u de verbindingsreeks niet op te slaan in uw code. Voor deze volgende sectie gebruiken we beheerde identiteiten om te verifiëren bij Azure Cosmos DB.
In een productieomgeving moet u een beheerde identiteit gebruiken met de minste bevoegdheden die nodig zijn. U kunt een of meer door de gebruiker toegewezen beheerde identiteiten maken en deze toewijzen aan het Azure Cosmos DB-account. Voor dit lab maken we een door het systeem toegewezen beheerde identiteit voor het Azure Cosmos DB-account.
- Navigeer in Azure Portal naar het Azure Cosmos DB-account dat u eerder hebt gemaakt.
- Selecteer Identiteit in het linkermenu onder Instellingen.
- Selecteer In het deelvenster Identiteitde optie Systeem toegewezen.
- Selecteer Aan voor de status.
- Selecteer Opslaan.
- Het duurt enkele minuten voordat de beheerde identiteit is gemaakt.
Zodra de beheerde identiteit is gemaakt, moeten we de beheerde identiteit de benodigde machtigingen toewijzen aan het Azure Cosmos DB-account. Tijd om RBAC (op rollen gebaseerd toegangsbeheer) te gebruiken om de beheerde identiteit de benodigde machtigingen toe te wijzen. Voor dit lab wijzen we de rol Inzender toe aan de beheerde identiteit, zodat deze gegevens kan lezen en schrijven naar het Azure Cosmos DB-account. In een productieomgeving moet u de rol met minimale bevoegdheden toewijzen die nodig is.
- Navigeer in Azure Portal naar het Azure Cosmos DB-account dat u eerder hebt gemaakt.
- Selecteer toegangsbeheer (IAM) in het linkermenu onder Instellingen.
- Selecteer + Toevoegen en voeg vervolgens roltoewijzing toe.
- Selecteer Inzender onder de rol Bevoegde beheerder, selecteer Volgende.
- Selecteer onder Ledenbeheerde identiteit en selecteer vervolgens + Leden selecteren.
- Zoek in het deelvenster Beheerde identiteiten selecteren naar de beheerde identiteit die u eerder hebt gemaakt, selecteer deze en selecteer vervolgens Beoordelen en toewijzen.
U hebt nu een beheerde identiteit toegewezen aan het Azure Cosmos DB-account met de benodigde machtigingen. We gaan nu de beheerde identiteit gebruiken om te verifiëren bij het Azure Cosmos DB-account.
Extensieopdrachten gebruiken om gegevens te beheren die zijn opgeslagen in de API van Azure Cosmos DB voor MongoDB
Hoewel de vorige code identiek zou zijn tussen het maken van verbinding met een MongoDB-server en vervolgens verbinding met ons Azure Cosmos DB voor MongoDB-account, maakt de verbinding mogelijk geen gebruik van Azure Cosmos DB-functies. Dit betekent dat u de standaardstuurprogrammamethoden gebruikt om onze verzamelingen te maken, maar ook de standaardparameters van het Azure Cosmos DB-account gebruikt om deze verzamelingen te maken. We kunnen dus geen parameters voor het maken definiëren, zoals onze doorvoer, shardingsleutel of instellingen voor automatisch schalen met behulp van deze methoden.
Met behulp van de API van Azure Cosmos DB voor MongoDB kunt u profiteren van de voordelen van Cosmos DB. Deze voordelen zijn onder andere wereldwijde distributie, automatische sharding, hoge beschikbaarheid, latentiegaranties, automatische versleuteling at rest, back-ups en nog veel meer. Plus het extra voordeel van het behouden van uw investeringen in uw MongoDB-app. U kunt communiceren met de API van Azure Cosmos DB voor MongoDB met behulp van een van de open source MongoDB-clientstuurprogramma's. De API van Azure Cosmos DB voor MongoDB maakt het gebruik van bestaande clientstuurprogramma's mogelijk door zich aan het MongoDB-wireprotocol te houden.
We gaan code maken waarmee we een verzameling kunnen maken en de shardingsleutel en doorvoer kunnen definiëren.
Open de Azure Cloud Shell in nog niet geopend.
Voer de volgende opdracht uit om de code-editor te openen.
cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/node code App.jscd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/java/AzureApp code ./src/main/java/com/fabrikam/App.javacd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/python code App.pycd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/csharp code app.csKopieer de volgende code naar het bestand.
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);De volgende stap maakt verbinding met de werknemersdatabase . Als deze database niet bestaat, wordt deze alleen gemaakt als er ook een verzameling in dezelfde verbinding wordt gemaakt of met behulp van extensieopdrachten. Voeg het volgende toe aan het script in de editor.
// 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");Tot nu toe lijkt het veel op de code in de vorige sectie. In deze stap maken we gebruik van de extensieopdrachten en maken we een aangepaste actie. Met deze actie kunnen we de doorvoer en de shardingsleutel van de verzameling definiëren. De stap geeft Azure Cosmos DB op zijn beurt de parameters die moeten worden gebruikt bij het maken van de verzameling. Voeg het volgende toe aan het script in de editor.
// 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""}");De rest is identiek aan het vorige voorbeeld. We maken verbinding met de verzameling, voegen enkele rijen in, voeren ten slotte een query uit en voeren een rij terug uit. Voeg het volgende toe aan het script in de editor.
// 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); } }Het script moet er als volgt uitzien:
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); } }Laten we het programma opslaan. Selecteer in de rechterbovenhoek van de code-editor en selecteer Opslaan (of Ctrl+S). Selecteer nu Sluit Editor (of Ctrl+Q) om terug te gaan naar de Shell.
Nu gaan we de app uitvoeren met de volgende opdracht.
node App.jsmvn clean compile exec:javapython App.pydotnet runDit zou een vergelijkbaar resultaat moeten retourneren als het resultaat hieronder. Dit betekent dat we de database, verzameling en er een document aan hebben toegevoegd.
{ _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'Deze laatste resultatenset heeft echter alleen bevestigd dat we inderdaad een database, verzameling en documenten hebben gemaakt, maar hoe zit het met onze shardsleutel en doorvoer, zijn ze echt gewijzigd? In Cloud Shell gaan we de volgende opdrachten uitvoeren om te controleren of de wijzigingen zijn doorgevoerd.
Laten we controleren of de shard key is gewijzigd naar EmployeeId (de standaard is id). Vergeet niet om de naam van de resourcegroep en de accountnaam te wijzigen naar de namen die we aan het begin van dit lab hebben opgeslagen.
az cosmosdb mongodb collection show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734Het resultaat moet de eigenschap shardKey bevatten: {"EmployeeId": "Hash"}.
We gaan controleren of de doorvoer is gewijzigd in 1000 (de standaardwaarde is 400). Vergeet niet om de naam van de resourcegroep en de accountnaam te wijzigen naar de namen die we aan het begin van dit lab hebben opgeslagen.
az cosmosdb mongodb collection throughput show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734Het resultaat moet de eigenschap doorvoer bevatten: 1000.
Deze code illustreerde de kracht van het gebruik van uitgebreide opdrachten in onze code, waarmee we de parameters voor het maken van Azure Cosmos DB kunnen definiëren. Hierdoor kunnen we profiteren van de manier waarop onze verzamelingen worden gemaakt en verwerkt door Azure Cosmos DB.
Zodra u deze oefening hebt voltooid, gaat u verder met de kennistoetsvragen voor deze module.