Latihan - Membuat aplikasi MongoDB DB menggunakan Azure Cosmos DB untuk MongoDB
Saatnya untuk secara terprogram memeriksa cara membuat database Azure Cosmos DB untuk MongoDB, koleksi, dan menambahkan beberapa data.
Latihan ini dapat diselesaikan menggunakan kotak pasir Microsoft Learn, yang menyediakan langganan Azure sementara. Untuk mengaktifkan langganan kotak pasir, Anda harus masuk menggunakan akun Microsoft. Langganan kotak pasir dihapus secara otomatis saat Anda menyelesaikan modul ini. Setelah kotak pasir diaktifkan, masuk ke portal Microsoft Azure menggunakan kredensial untuk langganan kotak pasir Anda. Pastikan Anda bekerja di direktori Microsoft Learn Sandbox - ditunjukkan di kanan atas portal di bawah ID pengguna Anda. Jika tidak, pilih ikon pengguna dan ubah direktori.
Petunjuk / Saran
Jika mau, Anda dapat menggunakan langganan Azure Anda sendiri. Untuk melakukannya, masuk ke portal Microsoft Azure menggunakan kredensial untuk langganan Anda. Pastikan Anda bekerja di direktori yang berisi langganan Anda - yang diperlihatkan di kanan atas di bawah ID pengguna Anda. Jika tidak, pilih ikon pengguna dan ubah direktori.
Membuat aplikasi MongoDB menggunakan Node.js Azure Cosmos DB untuk MongoDB
Membuat aplikasi MongoDB menggunakan Java Azure Cosmos DB untuk MongoDB
Membuat aplikasi MongoDB menggunakan Python Azure Cosmos DB untuk MongoDB
Membuat aplikasi MongoDB menggunakan C# Azure Cosmos DB untuk MongoDB
Dalam latihan ini, Anda membuat akun Azure Cosmos DB untuk MongoDB, database, koleksi, dan menambahkan beberapa dokumen ke koleksi. Anda melihat bahwa kode ini identik dengan bagaimana Anda akan terhubung ke database MongoDB apa pun. Anda kemudian membuat koleksi menggunakan perintah ekstensi yang memungkinkan Anda menentukan throughput di Unit Permintaan/detik (RU) untuk koleksi.
Mempersiapkan lingkungan pengembangan Anda
Jika Anda tidak memiliki akun dan lingkungan Azure Cosmos DB tempat Anda mengerjakan lab ini, ikuti langkah-langkah berikut untuk melakukannya. Jika tidak, buka bagian Tambahkan kode untuk membuat database, koleksi, dan dokumen ke file App.js .
Jika Anda bukan lingkungan dan akun Azure Cosmos DB tempat Anda mengerjakan lab ini, ikuti langkah-langkah berikut untuk melakukannya. Jika tidak, buka bagian Tambahkan kode untuk membuat database, koleksi, dan dokumen ke file App.java .
Jika Anda bukan akun dan lingkungan Azure Cosmos DB tempat Anda mengerjakan lab ini, ikuti langkah-langkah berikut untuk melakukannya. Jika tidak, buka bagian Tambahkan kode untuk membuat database, koleksi, dan dokumen ke file App.py .
Jika Anda tidak memiliki lingkungan dan akun Azure Cosmos DB tempat Anda mengerjakan lab ini, ikuti langkah-langkah berikut untuk melakukannya. Jika tidak, buka bagian Tambahkan kode untuk membuat database, koleksi, dan dokumen ke file app.cs .
Di Azure Cloud Shell, salin dan tempel perintah berikut.
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.shPetunjuk / Saran
Jika Anda tidak menggunakan kotak pasir untuk lab, dan Anda ingin menentukan lokasi tempat Anda ingin membuat database dan objek penyimpanan, tambahkan parameter -l LOCATIONNAME ke panggilan init.sh . Selain itu, jika Anda ingin menentukan grup sumber daya, tambahkan parameter -r YOURRRESOURCEGROUPNAMEHERE ke panggilan init.sh .
Catatan
Skrip bash ini akan membuat akun Azure Cosmos DB untuk MongoDB. Dibutuhkan waktu 5-10 menit untuk membuat akun ini sehingga mungkin saat yang tepat untuk mendapatkan secangkir kopi atau teh.
Petunjuk / Saran
Jika Anda kembali dan cloud shell Anda telah diatur ulang, jalankan perintah berikut di cloud shell untuk menggunakan Node versi 14, jika tidak, kode di bagian berikutnya akan gagal.
- source ~/.nvm/nvm.sh
- nvm install 14.0.0
- tautan npm mongodb
Ketika file init.sh bash selesai berjalan, salin di suatu tempat String Koneksi, nama Akun Cosmos DB, dan nama Grup Sumber Daya dikembalikan, kita akan membutuhkannya di bagian berikutnya. Anda juga dapat meninjau JSON yang ditampilkan oleh skrip pembuatan akun yang terletak sebelum string koneksi. Jika Anda melihat suatu tempat di tengah JSON, Anda akan melihat properti "kind": "MongoDB".
Catatan
Perhatikan bahwa String Koneksi, nama Akun Cosmos DB , dan nama Grup Sumber Daya juga dapat ditemukan menggunakan portal Microsoft Azure.
Menambahkan kode untuk membuat database, koleksi, dan dokumen ke file App.js
Sekarang saatnya menambahkan kode JavaScript untuk membuat Database, Kumpulan dan menambahkan dokumen ke kumpulan.
Menambahkan kode untuk membuat database, koleksi, dan dokumen ke file App.java
Sekarang saatnya menambahkan kode Java untuk membuat Database, Kumpulan dan menambahkan dokumen ke kumpulan.
Menambahkan kode untuk membuat database, koleksi, dan dokumen ke file App.py
Sekarang saatnya menambahkan kode Python untuk membuat Database, Kumpulan dan menambahkan dokumen ke kumpulan.
Menambahkan kode untuk membuat database, koleksi, dan dokumen ke file app.cs
Sekarang saatnya menambahkan kode C# untuk membuat Database, Kumpulan dan menambahkan dokumen ke kumpulan.
Di belum dibuka, buka Azure Cloud Shell.
Jalankan perintah berikut untuk membuka editor kode.
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.csSalin kode berikut ke file Aplikasi. Jangan lupa bahwa Anda perlu mengganti nilai uri untuk string koneksi yang disalin di bagian sebelumnya.
Bagian kode ini menggunakan driver MongoDB dan menggunakan string koneksi ke Azure Cosmos DB seperti Anda biasanya menggunakan string koneksi ke server MongoDB mana pun. Kode kemudian menentukan dan membuka koneksi ke akun 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);Langkah berikutnya tersambung ke database produk . Jika database ini tidak ada, database ini membuatnya hanya jika juga membuat koleksi dalam koneksi yang sama atau dengan menggunakan perintah ekstensi. Tambahkan hal berikut ke skrip di 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");Selanjutnya, kita menyambungkan ke kumpulan dokumen jika sudah ada, lalu menambahkan satu dokumen ke koleksi. Jika koleksi tidak ada, kode ini membuat koleksi jika juga melakukan operasi pada koleksi tersebut dalam koneksi yang sama (misalnya, seperti menambahkan dokumen ke koleksi) atau dengan menggunakan perintah ekstensi. Tambahkan hal berikut ke skrip di 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);Sekarang mari kita cari dokumen yang disisipkan dan menampilkannya ke shell. Tambahkan hal berikut ke skrip di 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); } }Terakhir, mari kita tutup koneksi. Tambahkan hal berikut ke skrip di 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.Skripnya akan terlihat seperti ini:
// 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); } }Mari kita lanjutkan dan menyimpan program. Pilih di sudut kanan atas editor kode dan pilih Simpan (atau Ctrl+S). Sekarang pilih Tutup Editor (atau Ctrl+Q) untuk kembali ke Shell.
Sekarang mari kita jalankan Aplikasi dengan perintah berikut.
node App.jsmvn clean compile exec:javapython App.pydotnet runSkrip ini harus mengembalikan hasil yang sama dengan yang berikut. Ini berarti bahwa kita membuat database, koleksi, dan menambahkan dokumen ke dalamnya.
{ _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'
Seperti yang dapat Anda perhatikan, kode ini adalah kode yang sama dengan yang akan Anda jalankan untuk membuat database, koleksi, dan dokumen pada database MongoDB. Jadi pemrograman untuk Azure Cosmos DB untuk MongoDB harus transparan bagi Anda jika Anda sudah terbiasa membuat aplikasi yang terhubung ke MongoDB.
Identitas Terkelola
Untuk beban kerja produksi, sebaiknya gunakan identitas terkelola untuk mengautentikasi ke Azure Cosmos DB. Dengan cara ini, Anda tidak perlu menyimpan string koneksi dalam kode Anda. Untuk bagian berikutnya ini, kita akan menggunakan identitas terkelola untuk mengautentikasi ke Azure Cosmos DB.
Pada lingkungan produksi, Anda harus menggunakan identitas terkelola dengan hak istimewa paling sedikit yang diperlukan. Anda dapat membuat satu atau beberapa identitas terkelola yang ditetapkan pengguna dan menetapkannya ke akun Azure Cosmos DB. Untuk lab ini, mari kita buat identitas terkelola yang ditetapkan sistem untuk akun Azure Cosmos DB.
- Di portal Azure, navigasikan ke akun Azure Cosmos DB yang Anda buat sebelumnya.
- Di menu sebelah kiri, di bawah Pengaturan, pilih Identitas.
- Di panel Identitas , pilih Sistem yang ditetapkan.
- Pilih Aktif untuk Status.
- Pilih Simpan.
- Dibutuhkan satu atau dua menit agar identitas terkelola dibuat.
Setelah identitas terkelola dibuat, kita perlu menetapkan identitas terkelola izin yang diperlukan ke akun Azure Cosmos DB. Waktu untuk menggunakan RBAC (Kontrol Akses Berbasis Peran) untuk menetapkan identitas terkelola izin yang diperlukan. Untuk lab ini, kami menetapkan peran Kontributor ke identitas terkelola untuk memungkinkannya membaca dan menulis data ke akun Azure Cosmos DB. Di lingkungan produksi, Anda harus menetapkan peran hak istimewa paling sedikit yang diperlukan.
- Di portal Azure, navigasikan ke akun Azure Cosmos DB yang Anda buat sebelumnya.
- Di menu sebelah kiri, di bawah Pengaturan, pilih Kontrol akses (IAM).
- Pilih + Tambahkan lalu Tambahkan penetapan peran.
- Di bawah peran Administrator istimewa, pilih Kontributor, pilih Berikutnya.
- Di bawah Anggota pilih Identitas Terkelola, lalu + Pilih anggota.
- Di panel Pilih identitas terkelola , cari identitas terkelola yang Anda buat sebelumnya, pilih identitas tersebut, lalu pilih Tinjau + tetapkan.
Anda sekarang memiliki identitas terkelola yang ditetapkan ke akun Azure Cosmos DB dengan izin yang diperlukan. Sekarang mari kita gunakan identitas terkelola untuk mengautentikasi ke akun Azure Cosmos DB.
Menggunakan perintah ekstensi untuk mengelola data yang disimpan di API Azure Cosmos DB untuk MongoDB
Meskipun kode sebelumnya, akan identik antara menyambungkan ke Server MongoDB lalu koneksi ke akun Azure Cosmos DB for MongoDB kami, koneksi mungkin tidak memanfaatkan fitur Azure Cosmos DB. Apa artinya menggunakan metode driver default untuk membuat koleksi kami, juga menggunakan parameter Akun Azure Cosmos DB default untuk membuat koleksi tersebut. Jadi kami tidak dapat menentukan parameter pembuatan seperti pengaturan throughput, kunci sharding, atau penskalaan otomatis menggunakan metode tersebut.
Dengan menggunakan API Azure Cosmos DB untuk MongoDB, Anda dapat menikmati manfaat Cosmos DB. Manfaat ini termasuk distribusi global, sharding otomatis, ketersediaan tinggi, jaminan latensi, otomatis, enkripsi saat tidak aktif, cadangan, dan banyak lagi. Ditambah manfaat tambahan untuk mempertahankan investasi Anda di aplikasi MongoDB Anda. Anda dapat berkomunikasi dengan API Azure Cosmos DB untuk MongoDB menggunakan salah satu driver klien MongoDB sumber terbuka. API Azure Cosmos DB untuk MongoDB memungkinkan penggunaan driver klien yang ada dengan mengikuti protokol kabel MongoDB.
Mari kita buat beberapa kode yang memungkinkan kita membuat koleksi dan menentukan kunci sharding dan throughputnya.
Di belum dibuka, buka Azure Cloud Shell.
Jalankan perintah berikut untuk membuka editor kode.
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.csSalin kode berikut ke 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);Langkah berikutnya menyambungkan ke database karyawan . Jika database ini tidak ada, database ini membuatnya hanya jika juga membuat koleksi dalam koneksi yang sama atau dengan menggunakan perintah ekstensi. Tambahkan hal berikut ke skrip di 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");Sejauh ini terlihat seperti kode di bagian sebelumnya. Dalam langkah ini, kami memanfaatkan perintah ekstensi dan membuat tindakan kustom. Tindakan ini memungkinkan kita untuk menentukan throughput dan kunci sharding koleksi. Pada gilirannya, langkah tersebut memberi Azure Cosmos DB parameter yang akan digunakan saat membuat koleksi. Tambahkan hal berikut ke skrip di 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""}");Sisanya identik dengan contoh sebelumnya. Kami menyambungkan ke koleksi, menyisipkan beberapa baris, akhirnya mengkueri dan menghasilkan baris kembali. Tambahkan hal berikut ke skrip di 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); } }Skripnya akan terlihat seperti ini:
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); } }Mari kita lanjutkan dan menyimpan program. Pilih di sudut kanan atas editor kode dan pilih Simpan (atau Ctrl+S). Sekarang pilih Tutup Editor (atau Ctrl+Q) untuk kembali ke Shell.
Sekarang mari kita jalankan Aplikasi dengan perintah berikut.
node App.jsmvn clean compile exec:javapython App.pydotnet runPerintah ini akan menampilkan hasil yang serupa dengan yang di bawah ini. Ini berarti bahwa kami membuat database, kumpulan, dan menambahkan dokumen ke dalamnya.
{ _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'Namun set hasil terakhir ini hanya mengonfirmasi bahwa kami memang membuat database, kumpulan, dan dokumen, tetapi bagaimana dengan kunci shard dan throughput kami, apakah hal tersebut benar-benar berubah? Di Cloud Shell, jalankan perintah berikut untuk memverifikasi bahwa perubahan telah diterapkan.
Mari kita verifikasi bahwa kunci Shard kita berubah menjadi EmployeeId (defaultnya adalah id). Jangan lupa untuk mengubah nama grup sumber daya dan nama akun untuk nama yang kami simpan di awal lab ini.
az cosmosdb mongodb collection show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734Hasilnya harus mencakup properti "shardKey": {"EmployeeId": "Hash"}.
Mari kita verifikasi bahwa Throughput kita berubah menjadi 1000 (defaultnya adalah 400). Jangan lupa untuk mengubah nama grup sumber daya dan nama akun untuk nama yang kami simpan di awal lab ini.
az cosmosdb mongodb collection throughput show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734Hasilnya harus mencakup properti "throughput": 1000.
Kode ini menggambarkan kelebihan menggunakan perintah yang diperluas dalam kode kami, yang memungkinkan kami menentukan parameter pembuatan Azure Cosmos DB. Hal ini memungkinkan kami memanfaatkan pengendalian bagaimana kumpulan kami akan dibuat dan diproses oleh Azure Cosmos DB.
Setelah menyelesaikan latihan ini, lanjutkan ke pertanyaan pemeriksaan pengetahuan untuk modul ini.