Esercizio - Creare un'app di database MongoDB usando Azure Cosmos DB for MongoDB
È il momento di vedere come creare a livello di programmazione i database e le raccolte di Azure Cosmos DB for MongoDB e di aggiungere alcuni dati.
Questo esercizio può essere completato usando una sandbox di Microsoft Learn, che fornisce una sottoscrizione di Azure temporanea. Per attivare la sottoscrizione sandbox, è necessario accedere usando un account Microsoft. La sottoscrizione sandbox verrà eliminata automaticamente al termine di questo modulo. Dopo aver attivato la sandbox, accedere al portale di Azure usando le credenziali per la sottoscrizione sandbox. Assicurarsi di lavorare nella directory Sandbox di Microsoft Learn , indicata in alto a destra nel portale sotto l'ID utente. In caso contrario, selezionare l'icona utente e passare alla directory appropriata.
Suggerimento
Se si preferisce, è possibile usare la sottoscrizione di Azure personale. A tale scopo, accedere al portale di Azure usando le credenziali per la sottoscrizione. Assicurarsi di essere nella directory relativa alla sottoscrizione personale, indicata in alto a destra sotto l'ID utente. In caso contrario, selezionare l'icona utente e passare alla directory appropriata.
Creare un'app MongoDB usando Node.js Azure Cosmos DB per MongoDB
Creare un'app MongoDB usando Java Azure Cosmos DB per MongoDB
Creare un'app MongoDB con Python Azure Cosmos DB per MongoDB
Creare un'app MongoDB usando C# Azure Cosmos DB per MongoDB
In questo esercizio vengono creati un account di Azure Cosmos DB for MongoDB, un database e una raccolta, e vengono aggiunti alcuni documenti alla raccolta. Si noti che questo codice è identico per la modalità di connessione a qualsiasi database MongoDB. Creare quindi una raccolta usando i comandi di estensione che consentano di definire la velocità effettiva in UR/s per la raccolta.
Preparare l'ambiente di sviluppo
In assenza dell'account di Azure Cosmos DB e dell'ambiente di lavoro in questo lab, attenersi alla procedura seguente. In caso contrario, passare alla sezione Aggiungi il codice per creare i database, la raccolta e il documento al file App.js.
In assenza dell'ambiente e dell'account di Azure Cosmos DB di lavoro in questo lab, attenersi alla procedura seguente. In caso contrario, passare alla sezione Aggiungere il codice per creare i database, la raccolta e il documento nel file App.java.
In assenza dell'account di Azure Cosmos DB e dell'ambiente di lavoro in questo lab, attenersi alla procedura seguente. In caso contrario, passare alla sezione Aggiungere il codice per creare i database, le raccolte e i documenti nel file App.py.
In assenza dell'ambiente e dell'account di Azure Cosmos DB di lavoro in questo lab, attenersi alla procedura seguente. In caso contrario, passare alla sezione Aggiungere il codice per creare i database, la raccolta e il documento nel file app.cs.
Copiare e incollare i comandi seguenti 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.shSuggerimento
Se non si usa la sandbox per il lab e si vuole specificare il percorso in cui si vogliono creare gli oggetti di archiviazione e di database, aggiungere un parametro -l LOCATIONNAME alla chiamata init.sh . Inoltre, se si vuole specificare un gruppo di risorse, aggiungere un parametro -r YOURRRESOURCEGROUPNAMEHERE alla chiamata init.sh .
Nota
Questo script Bash creerà l'account Azure Cosmos DB for MongoDB. La creazione di questo account può richiedere 5-10 minuti , quindi potrebbe essere un buon momento per prendere una tazza di caffè o tè.
Suggerimento
Se al termine si nota che Cloud Shell è stato reimpostato, eseguire i comandi seguenti in Cloud Shell per usare Node versione 14. In caso contrario, il codice nella sezione successiva avrà esito negativo.
- source ~/.nvm/nvm.sh
- nvm install 14.0.0
- collegamento npm mongodb
Al termine dell'esecuzione del file bash init.sh , copiare in un punto qualsiasi la stringa di connessione, il nome dell'account Cosmos DB e il nome del gruppo di risorse restituiti, saranno necessari nella sezione successiva. È anche possibile esaminare il codice JSON restituito dallo script di creazione dell'account che si trova prima della stringa di connessione. Se si guarda da qualche parte al centro del codice JSON, dovrebbe essere visualizzata la proprietà "kind": "MongoDB".
Nota
Si noti che la stringa di connessione, il nome dell'account Cosmos DB e il nome del gruppo di risorse sono disponibili anche tramite il portale di Azure.
Aggiungere il codice per creare i database, la raccolta e il documento nel file App.js
Ora è il momento di aggiungere il codice JavaScript per creare un database, una raccolta e aggiungere un documento alla raccolta.
Aggiungere il codice per creare i database, la raccolta e il documento nel file App.java
Ora è il momento di aggiungere il codice Java per creare un database, una raccolta e aggiungere un documento alla raccolta.
Aggiungere il codice per creare i database, la raccolta e il documento nel file App.py
Ora è il momento di aggiungere il codice Phyton per creare un database, una raccolta e aggiungere un documento alla raccolta.
Aggiungere il codice per creare i database, la raccolta e il documento nel file app.cs
Ora è il momento di aggiungere il codice C# per creare un database, una raccolta e aggiungere un documento alla raccolta.
Se non è già aperto, aprire Azure Cloud Shell.
Eseguire il comando seguente per aprire l'editor di codice.
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.csCopiare il codice seguente nel file App. Non dimenticare che è necessario sostituire il valore URI per la stringa di connessione copiata nella sezione precedente.
Questa parte del codice usa i driver MongoDB e la stringa di connessione ad Azure Cosmos DB come si usa normalmente una stringa di connessione a qualsiasi server MongoDB. Il codice definisce e apre la connessione all'account Azure Cosmos DB.
// 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);Il passaggio successivo si connette al database dei prodotti . Se questo database non esiste, viene creato solo se viene creata anche una raccolta nella stessa connessione o tramite i comandi di estensione. Aggiungere il codice seguente allo script nell'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");Successivamente, ci si connette alla raccolta documenti , se esiste già, e quindi viene aggiunto un documento alla raccolta. Se la raccolta non esiste, questo codice crea la raccolta solo se viene eseguita anche un'operazione su tale raccolta nella stessa connessione (ad esempio aggiungendo un documento alla raccolta) o tramite i comandi di estensione. Aggiungere il codice seguente allo script nell'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);A questo punto, cercare il documento inserito per visualizzarlo nella shell. Aggiungere il codice seguente allo script nell'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); } }Infine, chiudere la connessione. Aggiungere il codice seguente allo script nell'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.Lo script dovrebbe essere simile al seguente:
// 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); } }Procedere e salvare il programma. Selezionare nell'angolo superiore destro dell'editor di codice e selezionare Salva (o CTRL+S). Ora selezionare Chiudi Editor (o Ctrl+Q) per tornare alla shell.
Eseguire l'App con il comando seguente.
node App.jsmvn clean compile exec:javapython App.pydotnet runQuesto script dovrebbe restituire un risultato simile al seguente. Ciò significa che sono stati creati il database, la raccolta e che vi è stato aggiunto un documento.
{ _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'
Come si può notare, questo codice è lo stesso che si eseguirebbe per creare un database, una raccolta e un documento in un database MongoDB. La programmazione per Azure Cosmos DB for MongoDB dovrebbe quindi essere trasparente se si ha già familiarità con la creazione di app che si connettono a MongoDB.
Identità gestite
Per i carichi di lavoro di produzione è consigliabile usare identità gestite per l'autenticazione in Azure Cosmos DB. In questo modo, non è necessario memorizzare la stringa di connessione nel codice. Per questa sezione successiva si useranno le identità gestite per l'autenticazione in Azure Cosmos DB.
In un ambiente di produzione è consigliabile usare un'identità gestita con i privilegi minimi necessari. È possibile creare una o più identità gestite assegnate dall'utente e assegnarle all'account Azure Cosmos DB. Per questo lab viene creata un'identità gestita assegnata dal sistema per l'account Azure Cosmos DB.
- Nel portale di Azure, passare all'account di Azure Cosmos DB creato in precedenza.
- Nel menu a sinistra, in Impostazioni, selezionare Identità.
- Nel riquadro Identità selezionare Sistema assegnato.
- Selezionare Sì per Stato.
- Selezionare Salva.
- La creazione dell'identità gestita richiede un 1-2 minuti.
Dopo aver creato l'identità gestita, è necessario assegnarle le autorizzazioni necessarie per l'account di Azure Cosmos DB. Tempo per usare il controllo degli accessi in base al ruolo (RBAC) per assegnare all'identità gestita le autorizzazioni necessarie. Per questo lab viene assegnato il ruolo Collaboratore all'identità gestita per consentire la lettura e la scrittura dei dati nell'account Azure Cosmos DB. In un ambiente di produzione è necessario assegnare il ruolo con privilegi minimi necessari.
- Nel portale di Azure, passare all'account di Azure Cosmos DB creato in precedenza.
- Nel menu a sinistra, in Impostazioni, selezionare Controllo di accesso (IAM).
- Selezionare + Aggiungi e quindi Aggiungi assegnazione di ruolo.
- Nel ruolo Amministratore con privilegi selezionare Collaboratore, selezionare Avanti.
- In Membri selezionare Identità gestita e quindi + Seleziona membri.
- Nel riquadro Seleziona identità gestite cercare l'identità gestita creata in precedenza, selezionarla e quindi selezionare Rivedi e assegna.
A questo punto, è disponibile un'identità gestita assegnata all'account di Azure Cosmos DB con le autorizzazioni necessarie. L'identità gestita ora viene usata per eseguire l'autenticazione all'account di Azure Cosmos DB.
Uso dei comandi dell'estensione per gestire i dati archiviati nell'API Azure Cosmos DB per MongoDB
Anche se il codice precedente sarebbe identico tra la connessione a un server MongoDB e la connessione all'account di Azure Cosmos DB for MongoDB, la connessione potrebbe non sfruttare le funzionalità di Azure Cosmos DB. Ciò significa che, usando i metodi dei driver predefiniti per creare le raccolte, vengono usati anche i parametri predefiniti dell'account di Azure Cosmos DB per creare tali raccolte. Non è possibile, quindi, definire parametri di creazione come la velocità effettiva, la chiave di partizionamento o le impostazioni di scalabilità automatica usando tali metodi.
Usando l'API di Azure Cosmos DB for MongoDB, è possibile sfruttare i vantaggi di Cosmos DB. Questi vantaggi includono distribuzione globale, partizionamento orizzontale automatico, disponibilità elevata, garanzie di latenza, automatismo, crittografia dei dati inattivi, backup e molti altri. Oltre al vantaggio aggiunto di preservare gli investimenti nell'app MongoDB. È possibile comunicare con l'API Azure Cosmos DB per MongoDB tramite uno dei driver open source del client MongoDB. L'API Azure Cosmos DB per MongoDB consente di usare i driver client esistenti aderendo al protocollo di collegamento MongoDB.
Verrà ora creato un codice che consentirà di creare una raccolta e di definirne la chiave di partizionamento e la velocità effettiva.
Se non è già aperto, aprire Azure Cloud Shell.
Eseguire il comando seguente per aprire l'editor di codice.
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.csCopiare il codice seguente nel file.
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);Il passaggio successivo si connette al database dei dipendenti . Se questo database non esiste, viene creato solo se viene creata anche una raccolta nella stessa connessione o tramite i comandi di estensione. Aggiungere il codice seguente allo script nell'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");Finora sembra molto simile al codice nella sezione precedente. In questo passaggio si sfruttano i comandi di estensione e si crea un'azione personalizzata. Questa azione consente di definire la velocità effettiva e la chiave di partizionamento orizzontale della raccolta. A sua volta, il passaggio fornisce ad Azure Cosmos DB i parametri da usare durante la creazione della raccolta. Aggiungere il codice seguente allo script nell'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""}");Il resto è identico all'esempio precedente. Ci si connette alla raccolta, si inseriscono alcune righe, infine si esegue una query e si restituisce una riga. Aggiungere il codice seguente allo script nell'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); } }Lo script dovrebbe essere simile al seguente:
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); } }Procedere e salvare il programma. Selezionare nell'angolo superiore destro dell'editor di codice e selezionare Salva (o CTRL+S). Ora selezionare Chiudi Editor (o Ctrl+Q) per tornare alla shell.
Eseguire l'App con il comando seguente.
node App.jsmvn clean compile exec:javapython App.pydotnet runIl risultato restituito dovrebbe essere simile al seguente. Ciò significa che sono stati creati il database, la raccolta e che vi è stato aggiunto un documento.
{ _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'Tuttavia, quest'ultimo set di risultati ha confermato solo l'effettiva creazione di un database, di una raccolta e dei documenti, ma è necessario verificare che la chiave di partizione e la velocità effettiva siano state realmente modificate. In Cloud Shell eseguire i comandi seguenti per verificare che le modifiche siano state applicate.
Verifichiamo che la nostra chiave di partizionamento sia stata modificata in EmployeeId (il valore predefinito è ID). Non dimenticare di modificare il nome del gruppo di risorse e il nome dell'account per i nomi salvati all'inizio di questo lab.
az cosmosdb mongodb collection show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734Il risultato deve includere la proprietà "shardKey": {"EmployeeId": "Hash"}.
Verificare che la velocità effettiva sia stata modificata in 1000 (il valore predefinito è 400). Non dimenticare di modificare il nome del gruppo di risorse e il nome dell'account per i nomi salvati all'inizio di questo lab.
az cosmosdb mongodb collection throughput show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734Il risultato deve includere la proprietà "throughput": 1000.
Questo codice illustra la potenza dell'uso dei comandi estesi nel codice, che consente di definire i parametri di creazione di Azure Cosmos DB. Ciò consente di sfruttare il controllo di come Azure Cosmos DB crea ed elabora le raccolte.
Dopo aver completato questo esercizio, continuare con le domande di verifica delle conoscenze per questo modulo.