Ejercicio: Creación de una aplicación de base de datos de MongoDB mediante Azure Cosmos DB for MongoDB
Es el momento de consultar mediante programación cómo crear las bases de datos de Azure Cosmos DB for MongoDB, las colecciones y agregar algunos datos.
Para completar este ejercicio, puede usar un espacio aislado de Microsoft Learn, que proporciona una suscripción de Azure temporal. Para activar la suscripción de espacio aislado, debe iniciar sesión con una cuenta de Microsoft. La suscripción de espacio aislado se elimina automáticamente al completar este módulo. Una vez que haya activado el espacio aislado, inicie sesión en Azure Portal con las credenciales de la suscripción de espacio aislado. Asegúrese de que está trabajando en el directorio Espacio aislado de Microsoft Learn, lo que se indica en la parte superior derecha del portal, debajo el identificador de usuario. Si no es así, seleccione el icono de usuario y cambie el directorio.
Sugerencia
Si lo prefiere, puede usar su propia suscripción de Azure. Para ello, inicie sesión en Azure Portal con las credenciales de su suscripción. Asegúrese de que está trabajando en el directorio que contiene la suscripción, lo que se indica en la parte superior derecha, debajo del identificador de usuario. Si no es así, seleccione el icono de usuario y cambie el directorio.
Creación de una aplicación de MongoDB mediante Azure Cosmos DB for MongoDB en Node.js
Creación de una aplicación de MongoDB mediante Azure Cosmos DB for MongoDB en Java
Creación de una aplicación de MongoDB mediante Azure Cosmos DB for MongoDB en Python
Creación de una aplicación de MongoDB mediante Azure Cosmos DB for MongoDB en C#
En este ejercicio, creará una cuenta de Azure Cosmos DB for MongoDB, una base de datos, una colección y agregará un par de documentos a la colección. Observará que este código es idéntico a cómo se conectar a cualquier base de datos de MongoDB. Después, creará una colección mediante comandos de extensión que le permiten definir el rendimiento en Unidades de solicitud por segundo (RU) para la colección.
Preparación del entorno de desarrollo
Si no tiene la cuenta y el entorno de Azure Cosmos DB con los que va a trabajar en este laboratorio, siga estos pasos para hacerlo. De lo contrario, vaya a la sección Adición del código para crear las bases de datos, la colección y el documento en el archivo App.js.
Si no tiene la cuenta y el entorno de Azure Cosmos DB con los que va a trabajar en este laboratorio, siga estos pasos para hacerlo. De lo contrario, vaya a la sección Adición del código para crear las bases de datos, la colección y el documento al archivo App.java.
Si no tiene la cuenta y el entorno de Azure Cosmos DB con los que va a trabajar en este laboratorio, siga estos pasos para hacerlo. De lo contrario, vaya a la sección Adición del código para crear las bases de datos, la colección y el documento al archivo App.py.
Si no tiene la cuenta y el entorno de Azure Cosmos DB con los que va a trabajar en este laboratorio, siga estos pasos para hacerlo. De lo contrario, vaya a la sección Adición del código para crear las bases de datos, la colección y el documento al archivo app.cs.
En Azure Cloud Shell, copie y pegue los siguientes comandos.
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
Sugerencia
Si no va a utilizar el espacio aislado para el laboratorio y quiere especificar la ubicación donde crear los objetos de base de datos y almacenamiento, agregue un parámetro -l NOMBRE_DE_LA_UBICACIÓN a la llamada init.sh. Además, si quiere especificar un grupo de recursos, agregue un parámetro -r NOMBRE_DEL_GRUPO_DE_RECURSOS a la llamada init.sh.
Nota
Este script de Bash creará la cuenta de Azure Cosmos DB for MongoDB. Puede tardar entre 5 y 10 minutos en crear esta cuenta, por lo que podría ser un buen momento para tomar un café o un té.
Sugerencia
Si vuelve y Cloud Shell se ha restablecido, ejecute los comandos siguientes en Cloud Shell para usar la versión 14 de Node; de lo contrario, se producirá un error en el código de la sección siguiente.
- source ~/.nvm/nvm.sh
- nvm install 14.0.0
- npm link mongodb
Cuando se complete la ejecución del archivo de Bash init.sh, copie en algún lugar la cadena de conexión, el nombre de la cuenta de Cosmos DB y el nombre del grupo de recursos devueltos, ya que los necesitará en la sección siguiente. También puede revisar el código JSON devuelto por el script de creación de la cuenta que se encuentra antes de la cadena de conexión. Si busca en el centro del código JSON, debería ver la propiedad "kind": "MongoDB".
Nota
Observe que la cadena de conexión, el nombre de la cuenta de Cosmos DB y el nombre del grupo de recursos también se pueden encontrar mediante Azure Portal.
Adición del código para crear las bases de datos, la colección y el documento al archivo App.js
Ahora es el momento de agregar el código de JavaScript para crear una base de datos, una colección y agregar un documento a la colección.
Adición del código para crear las bases de datos, la colección y el documento al archivo App.java
Ahora es el momento de agregar el código de Java para crear una base de datos, una colección y agregar un documento a la colección.
Adición del código para crear las bases de datos, la colección y el documento al archivo App.py
Ahora es el momento de agregar el código de Python para crear una base de datos, una colección y agregar un documento a la colección.
Adición del código para crear las bases de datos, la colección y el documento al archivo app.cs
Ahora es el momento de agregar el código de C# para crear una base de datos, una colección y agregar un documento a la colección.
Si todavía no está abierto, abra Azure Cloud Shell.
Ejecute el comando siguiente para abrir el 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 el código siguiente en el archivo App. No olvide que debe reemplazar el valor uri de la cadena de conexión que ha copiado en la sección anterior.
Esta parte del código usa los controladores de MongoDB y la cadena de conexión a Azure Cosmos DB como normalmente usaría una cadena de conexión a cualquier servidor de MongoDB. Después, el código define y abre la conexión a la cuenta de 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);
El siguiente paso se conecta a la base de datos products. Si esta base de datos no existe, solo se crea si también crea una colección en la misma conexión o mediante comandos de extensión. Agregue lo siguiente al script en el 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");
A continuación, se establece la conexión a la colección documents si ya existe y, después, se agrega un documento a la colección. Si la colección no existe, este código la crea si también realiza una operación en esa colección en la misma conexión (por ejemplo, agregar un documento a la colección) o mediante comandos de extensión. Agregue lo siguiente al script en el 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);
Ahora se buscará el documento que insertado y se mostrará en el shell. Agregue lo siguiente al script en el 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 último, se cierra la conexión. Agregue lo siguiente al script en el 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.
El script debe tener este aspecto:
// 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); } }
Ahora se guardará el programa. Seleccione la esquina superior derecha del editor de código y seleccione Guardar (o presione Ctrl+S). Ahora seleccione Cerrar editor (o presione Ctrl+Q) para volver al shell.
Ahora se ejecutará la aplicación con el siguiente comando.
node App.js
mvn clean compile exec:java
python App.py
dotnet run
Este script debe devolver un resultado similar al siguiente. Esto significa que se ha creado la base de datos, la colección y se le ha agregado 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'
Como puede observar, este código es el mismo que ejecutaría para crear una base de datos, una colección y un documento en una base de datos de MongoDB. Por tanto, la programación en Azure Cosmos DB for MongoDB debe ser transparente si ya está familiarizado con la creación de aplicaciones que se conectan a MongoDB.
Identidades administradas
En el caso de las cargas de trabajo de producción, se recomienda usar identidades administradas para autenticarse en Azure Cosmos DB. De este modo, no tiene que almacenar la cadena de conexión en el código. En esta sección siguiente, se usarán identidades administradas para la autenticación en Azure Cosmos DB.
En un entorno de producción, debería usar una identidad administrada con el privilegio mínimo necesario. Podría crear una o varias identidades administradas asignadas por el usuario y asignarlas a la cuenta de Azure Cosmos DB. Para este laboratorio, se creará una identidad administrada asignada por el sistema para la cuenta de Azure Cosmos DB.
- En Azure Portal, vaya hasta la cuenta de Azure Cosmos DB que ha creado antes.
- En el menú de la izquierda, en Configuración, seleccione Identidad.
- En el panel Identidad, seleccione Asignada por el sistema.
- Seleccione Activo para Estado.
- Seleccione Guardar.
- La identidad administrada tarda uno o dos minutos en crearse.
Una vez que se crea la identidad administrada, es necesario asignarle los permisos necesarios para la cuenta de Azure Cosmos DB. Es el momento de usar RBAC (Control de acceso basado en roles) para asignar los permisos necesarios a la identidad administrada. En este laboratorio, se asigna el rol de Colaborador a la identidad administrada para permitirle leer y escribir datos en la cuenta de Azure Cosmos DB. En un entorno de producción, debería asignar el rol de privilegio mínimo necesario.
- En Azure Portal, vaya hasta la cuenta de Azure Cosmos DB que ha creado antes.
- En el menú de la izquierda, en Configuración, seleccione Control de acceso (IAM).
- Seleccione + Agregar y después Agregar asignación de roles.
- En el rol Administrador con privilegios, seleccione Colaborador y después Siguiente.
- En Miembros seleccione Identidad administrada y después + Seleccionar miembros.
- En el panel Seleccionar identidades administradas, busque la identidad administrada que ha creado antes, selecciónela y, después, seleccione Revisar y asignar.
Ahora tiene una identidad administrada asignada a la cuenta de Azure Cosmos DB con los permisos necesarios. A continuación se usará la identidad administrada para la autenticación en la cuenta de Azure Cosmos DB.
Uso de comandos de extensión para administrar datos almacenados en Azure Cosmos DB API para MongoDB
Aunque el código anterior sería idéntico entre la conexión a un servidor de MongoDB y la posterior conexión a la cuenta de Azure Cosmos DB for MongoDB, es posible que esto no saque provecho de las características de Azure Cosmos DB. Esto significa que al usar los métodos de controlador predeterminados para crear las colecciones, también se usan los parámetros predeterminados de la cuenta de Azure Cosmos DB para crearlas. Por tanto, no se pueden definir parámetros de creación como los de rendimiento, clave de particionamiento o configuración de escalado automático mediante esos métodos.
Mediante la API de Azure Cosmos DB para MongoDB, puede disfrutar de las ventajas de Cosmos DB. Entre estas ventajas se incluyen la distribución global, el particionamiento automático, la alta disponibilidad, garantías de latencia, cifrado en reposo, copias de seguridad y mucho más. Además, la ventaja adicional de conservar las inversiones en la aplicación de MongoDB. Puede comunicarse con la API de Azure Cosmos DB para MongoDB con cualquiera de los controladores de cliente de MongoDB de código abierto. La API de Azure Cosmos DB para MongoDB permite usar los controladores cliente existentes mediante la adhesión al protocolo de conexión de MongoDB.
Ahora se creará código que permita crear una colección y definir su clave de particionamiento y rendimiento.
Si todavía no está abierto, abra Azure Cloud Shell.
Ejecute el comando siguiente para abrir el 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 el siguiente código al archivo .
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);
El siguiente paso establece la conexión a la base de datos employees. Si esta base de datos no existe, solo se crea si también crea una colección en la misma conexión o mediante comandos de extensión. Agregue lo siguiente al script en el 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");
Hasta ahora se parece bastante al código de la sección anterior. En este paso, se sacará provecho de los comandos de extensión y se creará una acción personalizada. Esta acción permite definir el rendimiento y la clave de particionamiento de la colección. A su vez, el paso proporciona a Azure Cosmos DB los parámetros que se usarán al crear la colección. Agregue lo siguiente al script en el 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""}");
El resto es idéntico al ejemplo anterior. Se establece la conexión con la colección, se insertan algunas filas, se realiza una consulta y se genera una fila. Agregue lo siguiente al script en el 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); } }
El script debe tener este aspecto:
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); } }
Ahora se guardará el programa. Seleccione la esquina superior derecha del editor de código y seleccione Guardar (o presione Ctrl+S). Ahora seleccione Cerrar editor (o presione Ctrl+Q) para volver al shell.
Ahora se ejecutará la aplicación con el siguiente comando.
node App.js
mvn clean compile exec:java
python App.py
dotnet run
Esto debe devolver un resultado similar al siguiente. Significa que se ha creado la base de datos, la colección y se le ha agregado 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'
Pero este último conjunto de resultados solo ha confirmado que realmente se han creado una base de datos, una colección y documentos, pero ¿realmente han cambiado la clave de partición y el rendimiento? En Cloud Shell se ejecutará los comandos siguientes para comprobar que los cambios han surtido efecto.
Ahora se comprobará que la clave de partición ha cambiado a EmployeeId (el valor predeterminado es id). No olvide cambiar el nombre del grupo de recursos y el nombre de la cuenta por los nombres que se han guardado al principio de este laboratorio.
az cosmosdb mongodb collection show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734
El resultado debe incluir la propiedad "shardKey": {"EmployeeId": "Hash"}.
Ahora se comprobará que el rendimiento ha cambiado a 1000 (el valor predeterminado es 400). No olvide cambiar el nombre del grupo de recursos y el nombre de la cuenta por los nombres que se han guardado al principio de este laboratorio.
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
El resultado debe incluir la propiedad "throughput": 1000.
Este código ilustra la eficacia de usar comandos extendidos en el código, lo que permite definir los parámetros de creación de Azure Cosmos DB. Esto permite sacar provecho de controlar cómo se crearán y procesarán las colecciones mediante Azure Cosmos DB.
Una vez que complete este ejercicio, continúe con las preguntas de prueba de conocimientos de este módulo.