Membuat akun, database, dan koleksi menggunakan Azure Cosmos DB untuk MongoDB
Azure Cosmos DB adalah platform-as-a-service (PaaS) yang terkelola sepenuhnya. Untuk menggunakan layanan ini, kita perlu terlebih dahulu membuat akun Azure Cosmos DB di bawah langganan kita. Setelah akun dibuat, kita kemudian dapat menambahkan database, koleksi, dan dokumen di dalamnya.
Kami melihat beberapa cara untuk membuat elemen model Azure Cosmos DB for MongoDB yang berbeda.
Membuat akun, database, dan kontainer untuk Azure Cosmos DB for MongoDB menggunakan portal Azure
Salah satu cara untuk membuat akun Azure Cosmos DB kami dan elemennya, adalah menggunakan portal Microsoft Azure. Dalam contoh ini, kami menggunakan portal Azure untuk membuat akun Azure Cosmos DB menggunakan Azure Cosmos DB untuk MongoDB. Kami kemudian menambahkan database dan koleksi. Untuk saat ini, jangan khawatir tentang mengisi pengaturan yang lebih canggih yang kami bahas secara lebih rinci dalam modul selanjutnya. Untuk contoh ini, mari kita tinjau tab Dasar. Mari kita buat akun dan elemennya.
Membuat akun untuk Azure Cosmos DB untuk MongoDB
Di portal Azure, Pilih + Buat Sumber Daya, pilih Azure Cosmos DB, dan Buat.
Pilih Azure Cosmos DB untuk MongoDB.
Masukkan parameter berikut.
- Langganan - Langganan Azure Anda saat ini.
- Grup Sumber Daya - Grup Sumber Daya Azure baru atau yang sudah ada untuk membuat akun Azure Cosmos DB.
- Nama Akun - Nama unik untuk akun Azure Cosmos DB Anda. Nama ini harus unik di seluruh Azure. URI akun Anda telah mongo.cosmos.azure.com ditambahkan ke nama akun Anda.
- Lokasi - Lokasi geografis yang menghosting akun Azure Cosmos DB Anda. Umumnya, Anda harus memilih lokasi yang dekat dengan pengguna atau aplikasi.
- Mode kapasitas - Seperti yang telah kita bahas di unit sebelumnya, Anda dapat memilih akun Anda untuk menggunakan Throughput yang disediakan atau Tanpa Server. Pilih Throughput yang disediakan untuk contoh ini.
- Terapkan Diskon Tingkat Gratis - Pilih Jangan Terapkan untuk contoh ini.
- Batasi total lalu lintas akun - Biarkan dalam keadaan tidak tercentang untuk contoh ini.
- Versi - Pilih 4.0.
Catatan
Untuk memanfaatkan fitur yang didukung dengan lebih baik, sebaiknya Anda menggunakan versi 3.6+ jika memungkinkan.
Pilih Tinjau + Buat, dan pada validasi yang berhasil, pilih Buat.
Catatan
Diperlukan beberapa menit untuk membuat akun Azure Cosmos DB Anda.
Membuat database dan kontainer untuk Azure Cosmos DB untuk MongoDB
Membuat database dan kontainer di portal Microsoft Azure sangatlah mudah, mari kita buat database terlebih dahulu.
Pada menu sebelah kiri akun Azure Cosmos DB for MongoDB, pilih Data Explorer.
Pilih menu dropdown di sebelah kanan ikon Kumpulan Baru dan pilih Database Baru.
Beri database Anda nama baru di bawah kotak teks ID Database.
Meskipun kami dapat menentukan penyediaan throughput dalam dialog Database Baru, dalam banyak kasus, Anda akan memilih penyediaan throughput di tingkat kontainer. Mari hapus centang pada kotak centang Sediakan throughput dan pilih Oke untuk contoh ini.
Sekarang kita akan melihat database baru kita di bawah bagian API MONGO. Saatnya membuat kumpulan baru.
Pilih ikon Kumpulan Baru.
Masukkan parameter berikut di bawah dialog Kumpulan Baru.
- Nama database - Anda melihat bahwa Anda memiliki dua opsi di sini, Buat baru, atau Gunakan yang sudah ada. Opsi ini memungkinkan Anda membuat database baru pada saat membuat kumpulan baru. Karena kita telah membuat database baru pada langkah sebelumnya, pilih Gunakan yang ada dan pilih nama database dari opsi menu dropdown.
- Id koleksi - Parameter ini adalah nama yang Anda berikan pada koleksi Anda.
-
Sharding - Kami biasanya ingin memilih Sharded. Opsi ini memungkinkan Azure Cosmos DB membuat wadah yang dipartisi di beberapa penyewa berdasarkan kunci Shard. Dengan kontainer besar, Azure Cosmos DB menyebarkan penyewa Anda di beberapa node fisik untuk mencapai skala yang tinggi. Kami membahas pemecahan secara lebih rinci di bawah modul Desain . Pilih Sharded.
- Kunci Shard - Memilih opsi Sharded mengharuskan Anda untuk menambahkan Kunci Shard. Kunci ini adalah kunci partisi yang menentukan strategi partisi Anda. Misalnya, dalam koleksi IoT (Internet of Things) itu bisa /deviceid atau mungkin /region, tergantung pada strategi partisi yang Anda pilih. Kami membahas strategi pemartisian secara lebih rinci di bawah modul Desain .
- Kotak centang untuk menyediakan throughput khusus untuk koleksi ini - Biasanya Anda ingin menyetel throughput koleksi Anda sebagai Penyesuaian Otomatis atau Manual. Pengaturan ini memungkinkan Anda memiliki kontrol yang lebih baik atas biaya kumpulan individu Anda. Kami membahas throughput secara lebih rinci dalam modul Desain . Untuk saat ini, centang kotak dan pilih Skalakan Otomatis.
- Throughput Koleksi atau Koleksi Maks RU/s - Tergantung apakah Anda memilih Manual atau Skala Otomatis, Anda perlu memasukkan Throughput Koleksi atau Koleksi Maks RU/s masing-masing, atau dengan kata lain mode throughput. Perbedaan utamanya adalah bahwa dalam mode Manual membebankan jumlah RU yang dipilih terlepas dari apakah Anda menggunakannya atau tidak. Skala otomatis hanya membebankan sesuai penggunaan Anda hingga RU/s Maks yang Anda pilih. Dalam kedua kasus, kumpulan data Anda mulai diperlambat setelah throughputnya mencapai nilai yang dipilih. Biarkan nilai yang telah ditentukan untuk contoh ini.
- Penyimpanan Analitik - Penyimpanan analitik Azure Cosmos DB berada di luar cakupan pelajaran ini. Tinjau artikel Apa itu penyimpanan analitik Azure Cosmos DB untuk informasi selengkapnya tentang topik tersebut.
- Tingkat Lanjut/Pengindeksan - Kami membahas indeks secara lebih rinci di bawah modul Desain . Biarkan kotak centang dicentang.
Seharusnya sekarang kita memiliki sebuah database dan satu koleksi untuk dihubungkan. Di unit berikutnya, kita akan membahas lebih detail tentang menyambungkan ke akun Azure Cosmos DB for MongoDB. Sebelum itu, mari kita tinjau cara lain untuk membuat database dan koleksi di Azure Cosmos DB for MongoDB.
Buat atau sambungkan ke database dan koleksi untuk Azure Cosmos DB for MongoDB
Anda harus dapat membuat atau menyambungkan ke akun Azure Cosmos DB for MongoDB menggunakan Java, Python, Node.js, .NET, atau bahasa pemrograman lainnya dengan driver MongoDB. Mari kita perkenalkan beberapa fungsi yang akan Anda gunakan untuk membuat elemen-elemen ini menggunakan beberapa bahasa yang berbeda. Pada awal modul ini, kami menyatakan bahwa pengembang dapat terus menggunakan driver MongoDB, SDK, dan alat yang mereka kenal untuk terhubung ke Azure Cosmos DB dan membuat aplikasi. Kami menggunakan driver tersebut beserta properti dan metodenya untuk memprogram akses dan operasi kami terhadap akun Azure Cosmos DB for MongoDB kami.
Membuat atau menyambungkan ke database untuk Azure Cosmos DB untuk MongoDB
Anda dapat menggunakan alat pengembangan favorit Anda untuk membuat aplikasi Azure Cosmos DB for MongoDB. Kami menggunakan driver MongoDB untuk setiap bahasa pemrograman masing-masing untuk membuat database dan koleksi kami. Mari kita tinjau kode untuk menyambungkan ke akun Azure Cosmos DB for MongoDB dan untuk menyambungkan ke database produk .
Node.js
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;
// Uncomment the corresponding lines for the authentication type you want to use.
// For system-assigned managed identity.
// const credential = new DefaultAzureCredential();
// For user-assigned managed identity.
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_COSMOS_TENANTID;
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const clientSecret = process.env.AZURE_COSMOS_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// 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 client = new MongoClient(connectionString);
try {
// Open the connection
await client.connect();
// Connect to the database "products"
const ProductDatabase = client.db('products');
// Add code to connect to a collection and add an entry here
} catch (err) {
console.error("An error occurred:", err);
} finally {
// Close the connection
await client.close();
}
}
main().catch((err) => console.error("Unhandled error:", err));
Java
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");
// Uncomment the corresponding lines for the authentication type you want to use.
// For system-assigned managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
// For user-assigned managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder()
// .managedIdentityClientId(System.getenv("AZURE_COSMOS_CLIENTID"))
// .build();
// For service principal.
// ClientSecretCredential defaultCredential = new ClientSecretCredentialBuilder()
// .clientId(System.getenv("AZURE_COSMOS_CLIENTID"))
// .clientSecret(System.getenv("AZURE_COSMOS_CLIENTSECRET"))
// .tenantId(System.getenv("AZURE_COSMOS_TENANTID"))
// .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
MongoDatabase ProductDatabase = mongoClient.getDatabase("products");
// Add code to connect to a collection and add an entry here
} catch (Exception e) {
e.printStackTrace();
} finally {
if (mongoClient != null) {
mongoClient.close();
}
}
}
}
Python
import os
import pymongo
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
# Environment variables
endpoint = os.getenv('AZURE_COSMOS_RESOURCEENDPOINT')
listConnectionStringUrl = os.getenv('AZURE_COSMOS_LISTCONNECTIONSTRINGURL')
scope = os.getenv('AZURE_COSMOS_SCOPE')
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity
# cred = ManagedIdentityCredential()
# For user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_COSMOS_TENANTID')
# client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# client_secret = os.getenv('AZURE_COSMOS_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# 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)
# To connect to the database, use the connection variable ("client" in this case), and the database name
ProductDatabase = client["products"]
# Add code to connect to a collection and add an entry here
C#
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 test
{
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");
// Uncomment the corresponding lines for the authentication type you want to use.
// For system-assigned identity.
// var tokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var tokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID")
// });
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_COSMOS_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTSECRET");
// var tokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// 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 "products" database.
var ProductDatabase = mongoClient.GetDatabase("products");
// Add code to connect to a collection and add an entry here.
}
}
Sesederhana itu, setelah kita terhubung menggunakan driver, kita membuat database baru, atau menunjuk ke yang sudah ada dengan GetDatabase atau metode serupa tergantung pada bahasanya. Aplikasi kita sekarang dapat menggunakan variabel ProductDatabase untuk merujuk ke database yang diinginkan. Membuat atau menyambungkan ke koleksi sama sederhananya dengan membuat database baru.
Membuat koleksi untuk Azure Cosmos DB untuk MongoDB
Untuk membuat atau mengakses koleksi yang ada, kami menggunakan metode dapatkan koleksi atau referensi tergantung pada bahasa pemrograman. Mari tambahkan beberapa kode ke contoh sebelumnya untuk membuat/menghubungkan ke kumpulan dan menambahkan satu entri pada kumpulan tersebut.
Node.js
// Add code to connect to a collection and add and find an entry here
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);
Java
// Add code to connect to a collection and add and find an entry here
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());
Python
# Add code to connect to a collection and add an entry here
collection = ProductDatabase["products"]
collection.insert_one({ "ProductId": 1, "name": "bread" })
C#
// Add code to connect to a collection and add an entry here
var ProductCollection = ProductDatabase.GetCollection<Products>("products");
Products Product = new Products {ProductId=1,name="bread"};
ProductCollection.InsertOne (Product);
Di unit berikutnya, kita akan melihat bagaimana tepatnya membuat string koneksi.
Gunakan perintah ekstensi MongoDB untuk mengelola data tersimpan di API Azure Cosmos DB untuk MongoDB
Seperti yang telah dibahas sebelumnya, Azure Cosmos DB for MongoDB memberi kami kemampuan untuk menggunakan driver dan kode yang sama dengan yang kami gunakan untuk mengakses dan membuat objek kami di server MongoDB untuk akun Azure Cosmos DB kami. Namun, dengan menggunakan kode tersebut, pembuatan database dan koleksi kami akan menggunakan parameter default Azure Cosmos DB. Untuk memanfaatkan fitur Azure Cosmos DB, kita harus dapat mengontrol parameter pembuatan database dan koleksi seperti throughput, penskalaan otomatis, penetapan kunci shard, dan menentukan indeks. Azure Cosmos DB for MongoDB memberi kita kemampuan ini dengan menggunakan perintah diperluas untuk menentukan parameter tersebut. Perintah ini memungkinkan kami membuat kode instruksi yang lebih tepat tentang cara membuat atau memodifikasi database dan kumpulan kami, khususnya untuk Azure Cosmos DB.
Azure Cosmos DB for MongoDB menyediakan perintah ekstensi untuk jenis permintaan berikut:
- Membuat database
- Perbarui database
- Mendapatkan database
- Buat koleksi
- Perbarui koleksi
- Dapatkan koleksi
Driver MongoDB menyediakan fungsi untuk menjalankan perintah terhadap database yang kami gunakan fungsi ini untuk mengirim perintah yang diperluas ke Azure Cosmos DB. Mari kita lihat kode untuk membuat koleksi perangkat IoT dengan throughput 2000 RU (Unit Permintaan) dan kunci pecahan DeviceId.
Node.js
// create the Devices collection with a throughput of 2000 RUs and with DeviceId as the sharding key
var result = IOTDatabase.command({customAction: "CreateCollection", collection: "Devices", offerThroughput: 2000, shardKey: "DeviceId"});
Java
// create the Devices collection with a throughput of 2000 RUs and with DeviceId as the sharding key
Document DevCollectionDef = new Document();
DevCollectionDef.append("customAction", "CreateCollection");
DevCollectionDef.append("collection", "Devices");
DevCollectionDef.append("offerThroughput", 2000);
DevCollectionDef.append("shardKey", "DeviceId");
Document result = IOTDatabase.runCommand(DevCollectionDef);
Python
# create the Devices collection with a throughput of 2000 RUs and with DeviceId as the sharding key
IOTDatabase.command({'customAction': "CreateCollection", 'collection': "Devices", 'offerThroughput': 2000, 'shardKey': "DeviceId"})
C#
// create the Devices collection with a throughput of 1000 RUs and with EmployeeId as the sharding key
var result = IOTDatabase.RunCommand<BsonDocument>(@"{customAction: ""CreateCollection"", collection: ""Devices"", offerThroughput: 2000, shardKey: ""DeviceId""}");
Dengan cara yang sama, kita dapat memodifikasi koleksi atau membuat atau memodifikasi database. Tinjau artikel Menggunakan perintah ekstensi MongoDB untuk mengelola data yang disimpan di API Azure Cosmos DB untuk MongoDB untuk informasi selengkapnya.