Exercício – Criar um aplicativo de banco de dados do MongoDB usando o Azure Cosmos DB for MongoDB
É hora de verificar o programa para ver como criar nossos bancos de dados e coleções do Azure Cosmos DB for MongoDB e adicionar alguns dados.
Este exercício pode ser concluído usando uma área restrita do Microsoft learn, que fornece uma assinatura temporária do Azure. Para ativar a assinatura da área restrita, você deve entrar usando um conta Microsoft. A assinatura da área restrita é excluída automaticamente quando você conclui este módulo. Depois que a área restrita for ativada, entre no portal do Azure usando as credenciais da sua assinatura da área restrita. Verifique se você está trabalhando no diretório da área restrita do Microsoft Learn, indicado no canto superior direito do portal, sob sua ID de usuário. Caso contrário, selecione o ícone de usuário e o troque o diretório.
Dica
Se preferir, você pode usar sua própria assinatura do Azure. Para fazer isso, entre no portal do Azure usando as credenciais da sua assinatura. Verifique se você está trabalhando no diretório que contém sua assinatura, indicado no canto superior direito sob sua ID de usuário. Caso contrário, selecione o ícone de usuário e o troque o diretório.
Criar um aplicativo do MongoDB usando o Azure Cosmos DB for MongoDB do Node.js
Criar um aplicativo do MongoDB usando o Azure Cosmos DB for MongoDB do Java
Criar um aplicativo do MongoDB usando o Azure Cosmos DB for MongoDB do Python
Criar um aplicativo do MongoDB usando o Azure Cosmos DB for MongoDB do C#
Neste exercício, você cria uma conta do Azure Cosmos DB for MongoDB, um banco de dados, uma coleção e adiciona alguns documentos à coleção. Observe que este código é idêntico ao que você usaria para se conectar a qualquer banco de dados do MongoDB. Em seguida, você cria uma coleção usando comandos de extensão que permitem definir a taxa de transferência em Unidades de Solicitação/s (RUs) para a coleção.
Preparar seu ambiente de desenvolvimento
Se você não tiver a conta e o ambiente do Azure Cosmos DB em que está trabalhando neste laboratório, siga estas etapas para fazê-lo. Caso contrário, vá para a seção Adicionar o código para criar os bancos de dados, a coleção e o documento no arquivo App.js.
Se você não tiver o ambiente e a conta do Azure Cosmos DB em que está trabalhando neste laboratório, siga estas etapas para fazê-lo. Caso contrário, vá para a seção Adicionar o código para criar os bancos de dados, a coleção e o documento no arquivo App.java.
Se você não tiver a conta e o ambiente do Azure Cosmos DB em que está trabalhando neste laboratório, siga estas etapas para fazê-lo. Caso contrário, vá para a seção Adicionar o código para criar os bancos de dados, a coleção e o documento no arquivo App.py.
Se você não tiver o ambiente e a conta do Azure Cosmos DB em que está trabalhando neste laboratório, siga estas etapas para fazê-lo. Caso contrário, vá para a seção Adicionar o código para criar os bancos de dados, a coleção e o documento no arquivo app.cs.
No Azure Cloud Shell, copie e cole os comandos a seguir.
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
Dica
Se você não estiver usando a área restrita no laboratório e quiser especificar a localização em que deseja criar o banco de dados e os objetos de armazenamento, adicione um parâmetro -l LOCATIONNAME à chamada a init.sh. Além disso, se você quiser especificar um grupo de recursos, adicione um parâmetro -r YOURRRESOURCEGROUPNAMEHERE à chamada a init.sh.
Observação
Esse script do bash criará a conta do Azure Cosmos DB for MongoDB. Pode levar de 5 a 10 minutos para criar essa conta, então pode ser uma boa hora para tomar uma xícara de café ou chá.
Dica
Se você voltar e o cloud shell tiver sido redefinido, execute os seguintes comandos no cloud shell para usar o Node versão 14, caso contrário, o código da próxima seção falhará.
- source ~/.nvm/nvm.sh
- nvm install 14.0.0
- npm link mongodb
Quando o arquivo bash init.sh terminar de ser executado, copie em algum lugar a Cadeia de Conexão, o Nome da Conta do Cosmos DB e o Nome do Grupo de Recursos retornados, pois precisaremos deles na próxima seção. Você também pode examinar o JSON retornado pelo script de criação da conta localizado antes da cadeia de conexão. Se você procurar em algum lugar nesse JSON, verá a propriedade "kind": "MongoDB".
Observação
Observe que a Cadeia de conexão, o Nome da conta do Cosmos DB e o Nome do grupo de recursos também podem ser encontrados usando o portal do Azure.
Adicione o código para criar os bancos de dados, a coleção e o documento ao arquivo App.js
Agora vamos adicionar nosso código JavaScript para criar um Banco de Dados, uma Coleção e adicionar um documento à coleção.
Adicione o código para criar os bancos de dados, a coleção e o documento ao arquivo App.java
Agora vamos adicionar nosso código Java para criar um Banco de Dados, uma Coleção e adicionar um documento à coleção.
Adicione o código para criar os bancos de dados, a coleção e o documento ao arquivo App.py
Agora vamos adicionar nosso código Python para criar um Banco de Dados, uma Coleção e adicionar um documento à coleção.
Adicione o código para criar os bancos de dados, a coleção e o documento ao arquivo app.cs
Agora vamos adicionar nosso código C# para criar um Banco de Dados, uma Coleção e adicionar um documento à coleção.
Se ainda não estiver aberto, abra o Azure Cloud Shell.
Execute o comando a seguir para abrir o editor de código.
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
Copie o código a seguir para o arquivo App. Não se esqueça de que você precisa substituir o valor de uri pela cadeia de conexão copiada na seção anterior.
Essa parte do código usa os drivers do MongoDB e usa a cadeia de conexão para o Azure Cosmos DB, assim como você normalmente usaria uma cadeia de conexão para qualquer servidor MongoDB. Em seguida, o código define e abre a conexão com a conta do 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);
A próxima etapa se conecta ao banco de dados de produtos. Se este banco de dados não existir, ele será criado somente se também criar uma coleção na mesma conexão ou usando comandos de extensão. Adicione o que vem a seguir ao script no 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");
Em seguida, conecte-se à coleção documentos se ela já existir e adicione um documento à coleção. Se a coleção não existir, este código criará a coleção se também executar uma operação nessa coleção na mesma conexão (por exemplo, adicionar um documento à coleção) ou usando comandos de extensão. Adicione o que vem a seguir ao script no 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);
Vamos agora procurar o documento inserido e exibi-lo no shell. Adicione o que vem a seguir ao script no 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); } }
Por fim, vamos fechar a conexão. Adicione o que vem a seguir ao script no 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.
O script deve parecer com este:
// 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); } }
Vamos continuar e salvar o programa. Selecione no canto superior direito do editor de código e escolha Salvar (ou Ctrl+S). Agora, selecione Fechar Editor (ou Ctrl+Q) para voltar ao Shell.
Vamos agora executar o Aplicativo com o seguinte comando.
node App.js
mvn clean compile exec:java
python App.py
dotnet run
Este script deve retornar um resultado semelhante ao seguinte. Isso significa que criamos o banco de dados, a coleção e adicionamos um documento a ela.
{ _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'
Como você pode perceber, este código é o mesmo que você executaria para criar um banco de dados, uma coleção e um documento em um banco de dados do MongoDB. Portanto, a programação relacionada ao Azure Cosmos DB for MongoDB será fácil se você já estiver familiarizado com a criação de aplicativos que se conectam ao MongoDB.
Identidades gerenciadas
Para cargas de trabalho de produção, recomendamos o uso de identidades gerenciadas para autenticar no Azure Cosmos DB. Dessa forma, você não precisa armazenar a cadeia de conexão no código. Na próxima seção, usaremos identidades gerenciadas para autenticar no Azure Cosmos DB.
Em um ambiente de produção, você deve usar uma identidade gerenciada com o mínimo de privilégios necessários. Você pode criar uma ou mais identidades gerenciadas atribuídas pelo usuário e atribuí-las à conta do Azure Cosmos DB. Para este laboratório, vamos criar uma identidade gerenciada atribuída pelo sistema para a conta do Azure Cosmos DB.
- No portal do Azure, navegue até a conta do Azure Cosmos DB criada anteriormente.
- No menu à esquerda, em Configurações, selecione Identidade.
- No painel Identidade, selecione Atribuído pelo sistema.
- Selecione Ativado para Status.
- Selecione Salvar.
- A criação da identidade gerenciada leva um ou dois minutos.
Depois que a identidade gerenciada for criada, será necessário atribuir à identidade gerenciada as permissões necessárias para a conta do Azure Cosmos DB. É hora de usar o RBAC (Controle de Acesso Baseado em Função) para atribuir à identidade gerenciada as permissões necessárias. Para este laboratório, atribuímos a função Colaborador à identidade gerenciada para permitir que ela leia e grave dados na conta do Azure Cosmos DB. Em um ambiente de produção, você deve atribuir a função com o mínimo de privilégios necessários.
- No portal do Azure, navegue até a conta do Azure Cosmos DB criada anteriormente.
- No menu à esquerda, em Configurações, selecione Controle de acesso (IAM).
- Selecione + Adicionar e depois Adicionar atribuição de função.
- Em Função de administrador privilegiado, selecione Colaborador e depois Avançar.
- Em Membros, selecione Identidade Gerenciada e depois + Selecionar membros.
- No painel Selecionar identidades gerenciadas, procure a identidade gerenciada criada anteriormente, selecione-a e depois selecione Revisar + atribuir.
Agora você tem uma identidade gerenciada atribuída à conta do Azure Cosmos DB com as permissões necessárias. Vamos agora usar a identidade gerenciada para autenticar na conta do Azure Cosmos DB.
Usar comandos de extensão para gerenciar dados armazenados na API do Azure Cosmos DB para MongoDB
Embora o código anterior seja idêntico entre a conexão a um Servidor MongoDB e a conexão à nossa conta do Azure Cosmos DB for MongoDB, a conexão pode não usufruir dos recursos do Azure Cosmos DB. Isso significa que, ao usar os métodos padrão do driver para criar nossas coleções, também usamos os parâmetros padrão da Conta do Azure Cosmos DB para criar essas coleções. Portanto, não podemos definir parâmetros de criação, como taxa de transferência, chave de fragmentação ou configurações de dimensionamento automático, usando esses métodos.
Ao usar a API do Azure Cosmos DB for MongoDB, você pode aproveitar os benefícios do Cosmos DB. Esses benefícios incluem distribuição global, fragmentação automática, alta disponibilidade, garantias de latência, criptografia em repouso, backups e muitos outros. Além do benefício adicional de preservar seus investimentos no aplicativo MongoDB. Você pode usar qualquer um dos drivers para cliente do MongoDB open-source para se comunicar com a API do Azure Cosmos DB para MongoDB. A API do Azure Cosmos DB para MongoDB permite o uso de drivers de cliente existentes ao aderir ao protocolo de transmissão do MongoDB.
Vamos criar um código que nos permita criar uma coleção e definir sua chave de fragmentação e taxa de transferência.
Se ainda não estiver aberto, abra o Azure Cloud Shell.
Execute o comando a seguir para abrir o editor de código.
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
Copie o código a seguir para o arquivo .
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);
A próxima etapa se conecta ao banco de dados de funcionários. Se este banco de dados não existir, ele será criado somente se também criar uma coleção na mesma conexão ou usando comandos de extensão. Adicione o que vem a seguir ao script no 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");
Até agora, parece muito com o código da seção anterior. Nesta etapa, usufruímos dos comandos de extensão e criamos uma ação personalizada. Esta ação nos permite definir a taxa de transferência e a chave de fragmentação da coleção. Por sua vez, a etapa fornece ao Azure Cosmos DB os parâmetros a serem usados ao criar a coleção. Adicione o que vem a seguir ao script no 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""}");
O restante é idêntico ao exemplo anterior. Conecte-se à coleção, insira algumas linhas, finalmente consulte e retorne uma linha. Adicione o que vem a seguir ao script no 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); } }
O script deve parecer com este:
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); } }
Vamos continuar e salvar o programa. Selecione no canto superior direito do editor de código e escolha Salvar (ou Ctrl+S). Agora, selecione Fechar Editor (ou Ctrl+Q) para voltar ao Shell.
Vamos agora executar o Aplicativo com o seguinte comando.
node App.js
mvn clean compile exec:java
python App.py
dotnet run
O resultado deverá ser semelhante ao que está abaixo. Isso significa que criamos o banco de dados, a coleção e adicionamos um documento a ela.
{ _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'
No entanto, este último conjunto de resultados só confirmou que realmente criamos um banco de dados, uma coleção e os documentos, mas e quanto à chave de fragmentação e à taxa de transferência, elas realmente mudaram? No Cloud Shell vamos executar os comandos a seguir para verificar se nossas alterações entraram em vigor.
Vamos verificar se nossa chave de fragmentação foi alterada para EmployeeId (o padrão é id). Não se esqueça de alterar o nome do grupo de recursos e o nome da conta com os nomes que salvamos no início deste laboratório.
az cosmosdb mongodb collection show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734
O resultado deve incluir a propriedade "shardKey": {"EmployeeId": "Hash"}.
Vamos verificar se nossa taxa de transferência foi alterada para 1000 (o padrão é 400). Não se esqueça de alterar o nome do grupo de recursos e o nome da conta com os nomes que salvamos no início deste laboratório.
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
O resultado deve incluir a propriedade "throughput": 1000.
Esse código ilustrou o potencial do uso de comandos estendidos em nosso código, o que nos permite definir os parâmetros de criação do Azure Cosmos DB. Isso nos permite aproveitar o controle de como nossas coleções serão criadas e processadas pelo Azure Cosmos DB.
Depois de concluir este exercício, continue nas perguntas de verificação de conhecimentos deste módulo.