Bu sayfada desteklenen kimlik doğrulama yöntemleri ve istemcileri gösterilir ve MongoDB için Azure Cosmos DB'yi Service Connector kullanarak diğer bulut hizmetlerine bağlamak için kullanabileceğiniz örnek kod gösterilir. Hizmet Bağlayıcısı'nı kullanmadan mongoDB için Azure Cosmos DB'ye diğer programlama dillerinde bağlanmaya devam edebilirsiniz. Bu sayfada, hizmet bağlantısını oluştururken elde ettiğiniz varsayılan ortam değişkeni adları ve değerleri (veya Spring Boot yapılandırması) da gösterilir.
Desteklenen işlem hizmetleri
Hizmet Bağlayıcısı, aşağıdaki işlem hizmetlerini MongoDB için Azure Cosmos DB'ye bağlamak için kullanılabilir:
- Azure App Service
- Azure Container Uygulamaları
- Azure İşlevleri
- Azure Kubernetes Service (AKS)
- Azure Spring Apps
Desteklenen kimlik doğrulama türleri ve istemci türleri
Aşağıdaki tabloda, hizmet bağlayıcısı kullanarak işlem hizmetinizi MongoDB için Azure Cosmos DB'ye bağlamak için hangi istemci türlerinin ve kimlik doğrulama yöntemlerinin desteklendiği gösterilmektedir. "Evet", birleşimin desteklendiğini, "Hayır" ise bunun desteklenmediğini gösterir.
İstemci türü |
Sistem tarafından atanan yönetilen kimlik |
Kullanıcı atamalı yönetilen kimlik |
Secret / connection string |
Service principal |
.NET |
Yes |
Yes |
Yes |
Yes |
Java |
Yes |
Yes |
Yes |
Yes |
Java - Spring Boot |
Hayır |
Hayır |
Yes |
Hayır |
Node.js |
Yes |
Yes |
Yes |
Yes |
Python |
Yes |
Yes |
Yes |
Yes |
Go |
Yes |
Yes |
Yes |
Yes |
Hiçbiri |
Yes |
Yes |
Yes |
Yes |
Bu tablo, java - Spring Boot istemci türü dışında, tablodaki tüm istemci türlerinin ve kimlik doğrulama yöntemlerinin desteklendiğini gösterir. Bu, yalnızca Gizli / bağlantı dizesi yöntemini destekler. Diğer tüm istemci türleri, Hizmet Bağlayıcısı'nı kullanarak MongoDB için Azure Cosmos DB'ye bağlanmak için herhangi bir kimlik doğrulama yöntemini kullanabilir.
Uyarı
Cosmos DB, yönetilen kimlik aracılığıyla kimlik doğrulamayı yerel olarak desteklemez. Bu nedenle, Hizmet Bağlayıcısı bağlantı dizesini almak için yönetilen kimliği kullanır ve bağlantı daha sonra bu bağlantı dizesi kullanılarak oluşturulur.
Varsayılan ortam değişkeni adları veya uygulama özellikleri ve örnek kod
İşlem hizmetlerini Azure Cosmos DB'ye bağlamak için aşağıdaki bağlantı ayrıntılarını kullanın. Bu sayfada ayrıca hizmet bağlantısını oluştururken elde ettiğiniz varsayılan ortam değişkeni adları ve değerleri (veya Spring Boot yapılandırması) ve örnek kod gösterilir. Aşağıdaki her örnek için , , <mongo-db-admin-user>
, <password>
, <Azure-Cosmos-DB-API-for-MongoDB-account>
, <subscription-ID>
, <resource-group-name>
ve <client-secret>
yer tutucu metinlerini <tenant-id>
kendi bilgilerinizle değiştirin. Adlandırma kuralları hakkında daha fazla bilgi için Hizmet Bağlayıcısı iç bilgileri makalesine bakın.
Sistem tarafından atanan yönetilen kimlik
Varsayılan ortam değişkeni adı |
Açıklama |
Örnek değer |
AZURE_COSMOS_LISTCONNECTIONSTRINGURL |
The URL to get the connection string |
https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-API-for-MongoDB-account>/listConnectionStrings?api-version=2021-04-15 |
AZURE_COSMOS_SCOPE |
Your managed identity scope |
https://management.azure.com/.default |
AZURE_COSMOS_RESOURCEENDPOINT |
Kaynak uç noktanız |
https://<Azure-Cosmos-DB-API-for-MongoDB-account>.documents.azure.com:443/ |
Örnek kod
Sistem tarafından atanan yönetilen kimliği kullanarak MongoDB için Azure Cosmos DB'ye bağlanmak için aşağıdaki adımlara ve koda bakın.
Cosmos DB, yönetilen kimlik aracılığıyla kimlik doğrulamasını yerel olarak desteklemediğinden, aşağıdaki kod örneğinde bağlantı dizesini almak için yönetilen kimliği kullanırız ve bu bağlantı dizesi kullanılarak bağlantı kurulur.
Bağımlılıkları yükleme
dotnet add package MongoDb.Driver
dotnet add package Azure.Identity
Azure.Identity istemci kitaplığını kullanarak yönetilen kimlik veya hizmet sorumlusu için erişim belirteci alın. Erişim belirtecini ve AZURE_COSMOS_LISTCONNECTIONSTRINGURL
kullanarak bağlantı dizesini alın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
using System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using MongoDB.Driver;
using Azure.Identity;
using System.Text.Json;
// you can retrieve the endpoint of the resource with the following env variable:
// Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT");
var listConnectionStringUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to 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 string[]{ scope }));
// Get the connection string.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
var response = await httpClient.PostAsync(new Uri(listConnectionStringUrl), null);
var responseBody = await response.Content.ReadAsStringAsync();
var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody);
var connectionString = connectionStrings["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
var client = new MongoClient(connectionString);
pom.xml dosyanıza aşağıdaki bağımlılıkları ekleyin:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
azure-identity
kullanarak yönetilen kimlik veya hizmet sorumlusu için bir erişim belirteci alın. Erişim belirtecini ve AZURE_COSMOS_LISTCONNECTIONSTRINGURL
kullanarak bağlantı dizesini alın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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;
String endpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT");
String listConnectionStringUrl = System.getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system 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();
// Get the access token.
AccessToken accessToken = defaultCredential.getToken(new TokenRequestContext().addScopes(new String[]{ scope })).block();
String token = accessToken.getToken();
// Get the connection string.
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(listConnectionStringUrl))
.header("Authorization", "Bearer " + token)
.POST()
.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 mongoClient = new MongoClient(uri);
Kimlik doğrulama türü Spring Boot için desteklenmiyor.
Bağımlılıkları yükleyin.
pip install pymongo
pip install azure-identity
Kodda, azure-identity
aracılığıyla erişim belirtecini alın ve bağlantı dizesini almak için kullanın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import os
import pymongo
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
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)
Bağımlılıkları yükleyin.
go get go.mongodb.org/mongo-driver/mongo
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
Kodda, azidentity
aracılığıyla erişim belirtecini alın ve bağlantı dizesini almak için kullanın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
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 identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// tenantid := os.Getenv("AZURE_COSMOS_TENANTID")
// clientsecret := os.Getenv("AZURE_COSMOS_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
// Acquire the access token.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{scope},
})
// Acquire the connection string.
client := &http.Client{}
req, err := http.NewRequest("POST", listConnectionStringUrl, nil)
req.Header.Add("Authorization", "Bearer " + token.Token)
resp, err := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
connectionString, err := result["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
clientOptions := options.Client().ApplyURI(connectionString).SetDirect(true)
c, err := mongo.Connect(ctx, clientOptions)
Bağımlılıkları yükleme
npm install mongodb
npm install --save @azure/identity
Kodda @azure/identity
aracılığıyla erişim belirtecini alın ve onu bağlantı dizisini almak için kullanın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const { MongoClient, ObjectId } = require('mongodb');
const axios = require('axios');
let endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT;
let listConnectionStringUrl = process.env.AZURE_COSMOS_LISTCONNECTIONSTRINGURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned 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;
// Acquire the access token.
var 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'];
const client = new MongoClient(connectionString);
Diğer diller için, MongoDB için Azure Cosmos DB'ye bağlanmak amacıyla, Hizmet Bağlayıcısı'nın ortam değişkenlerine ayarladığı MongoDB kaynak uç noktasını ve diğer özellikleri kullanabilirsiniz. Ortam değişkeni ayrıntıları için bkz . MongoDB için Azure Cosmos DB'yi Service Connector ile tümleştirme.
Kullanıcı atamalı yönetilen kimlik
Varsayılan ortam değişkeni adı |
Açıklama |
Örnek değer |
AZURE_COSMOS_LISTCONNECTIONSTRINGURL |
The URL to get the connection string |
https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-API-for-MongoDB-account>/listConnectionStrings?api-version=2021-04-15 |
AZURE_COSMOS_SCOPE |
Your managed identity scope |
https://management.azure.com/.default |
AZURE_COSMOS_CLIENTID |
İstemci kimliğiniz |
<client-ID> |
AZURE_COSMOS_RESOURCEENDPOINT |
Kaynak uç noktanız |
https://<Azure-Cosmos-DB-API-for-MongoDB-account>.documents.azure.com:443/ |
Örnek kod
Kullanıcı tarafından atanan yönetilen kimliği kullanarak MongoDB için Azure Cosmos DB'ye bağlanmak için aşağıdaki adımlara ve koda bakın.
Cosmos DB, yönetilen kimlik aracılığıyla kimlik doğrulamasını yerel olarak desteklemediğinden, aşağıdaki kod örneğinde bağlantı dizesini almak için yönetilen kimliği kullanırız ve bu bağlantı dizesi kullanılarak bağlantı kurulur.
Bağımlılıkları yükleme
dotnet add package MongoDb.Driver
dotnet add package Azure.Identity
Azure.Identity istemci kitaplığını kullanarak yönetilen kimlik veya hizmet sorumlusu için erişim belirteci alın. Erişim belirtecini ve AZURE_COSMOS_LISTCONNECTIONSTRINGURL
kullanarak bağlantı dizesini alın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
using System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using MongoDB.Driver;
using Azure.Identity;
using System.Text.Json;
// you can retrieve the endpoint of the resource with the following env variable:
// Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT");
var listConnectionStringUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to 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 string[]{ scope }));
// Get the connection string.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
var response = await httpClient.PostAsync(new Uri(listConnectionStringUrl), null);
var responseBody = await response.Content.ReadAsStringAsync();
var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody);
var connectionString = connectionStrings["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
var client = new MongoClient(connectionString);
pom.xml dosyanıza aşağıdaki bağımlılıkları ekleyin:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
azure-identity
kullanarak yönetilen kimlik veya hizmet sorumlusu için bir erişim belirteci alın. Erişim belirtecini ve AZURE_COSMOS_LISTCONNECTIONSTRINGURL
kullanarak bağlantı dizesini alın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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;
String endpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT");
String listConnectionStringUrl = System.getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system 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();
// Get the access token.
AccessToken accessToken = defaultCredential.getToken(new TokenRequestContext().addScopes(new String[]{ scope })).block();
String token = accessToken.getToken();
// Get the connection string.
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(listConnectionStringUrl))
.header("Authorization", "Bearer " + token)
.POST()
.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 mongoClient = new MongoClient(uri);
Kimlik doğrulama türü Spring Boot için desteklenmiyor.
Bağımlılıkları yükleyin.
pip install pymongo
pip install azure-identity
Kodda, azure-identity
aracılığıyla erişim belirtecini alın ve bağlantı dizesini almak için kullanın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import os
import pymongo
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
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)
Bağımlılıkları yükleyin.
go get go.mongodb.org/mongo-driver/mongo
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
Kodda, azidentity
aracılığıyla erişim belirtecini alın ve bağlantı dizesini almak için kullanın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
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 identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// tenantid := os.Getenv("AZURE_COSMOS_TENANTID")
// clientsecret := os.Getenv("AZURE_COSMOS_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
// Acquire the access token.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{scope},
})
// Acquire the connection string.
client := &http.Client{}
req, err := http.NewRequest("POST", listConnectionStringUrl, nil)
req.Header.Add("Authorization", "Bearer " + token.Token)
resp, err := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
connectionString, err := result["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
clientOptions := options.Client().ApplyURI(connectionString).SetDirect(true)
c, err := mongo.Connect(ctx, clientOptions)
Bağımlılıkları yükleme
npm install mongodb
npm install --save @azure/identity
Kodda @azure/identity
aracılığıyla erişim belirtecini alın ve onu bağlantı dizisini almak için kullanın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const { MongoClient, ObjectId } = require('mongodb');
const axios = require('axios');
let endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT;
let listConnectionStringUrl = process.env.AZURE_COSMOS_LISTCONNECTIONSTRINGURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned 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;
// Acquire the access token.
var 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'];
const client = new MongoClient(connectionString);
Diğer diller için, MongoDB için Azure Cosmos DB'ye bağlanmak amacıyla, Hizmet Bağlayıcısı'nın ortam değişkenlerine ayarladığı MongoDB kaynak uç noktasını ve diğer özellikleri kullanabilirsiniz. Ortam değişkeni ayrıntıları için bkz . MongoDB için Azure Cosmos DB'yi Service Connector ile tümleştirme.
Bağlantı dizesi
Uyarı
Microsoft, kullanılabilir en güvenli kimlik doğrulama akışını kullanmanızı önerir. Bu yordamda açıklanan kimlik doğrulama akışı, uygulamada çok yüksek düzeyde güven gerektirir ve diğer akışlarda mevcut olmayan riskleri taşır. Bu akışı yalnızca yönetilen kimlikler gibi diğer daha güvenli akışlar uygun olmadığında kullanmalısınız.
Spring Boot istemci türü
Varsayılan ortam değişkeni adı |
Açıklama |
Örnek değer |
spring.data.mongodb.database |
Veritabanınız |
<database-name> |
spring.data.mongodb.uri |
Veritabanı URI'niz |
mongodb://<mongo-db-admin-user>:<password>@<mongo-db-server>.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@<mongo-db-server>@ |
Diğer istemci türleri
Varsayılan ortam değişkeni adı |
Açıklama |
Örnek değer |
AZURE_COSMOS_CONNECTIONSTRING |
MongoDB API bağlantı dizesi |
mongodb://<mongo-db-admin-user>:<password>@<mongo-db-server>.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@<mongo-db-server>@ |
Örnek kod
MongoDB için Azure Cosmos DB'ye bağlantı dizesi kullanarak bağlanmak için aşağıdaki adımlara ve koda bakın.
Install dependency.
dotnet add package MongoDb.Driver
Hizmet Bağlayıcısı tarafından eklenen ortam değişkeninden bağlantı dizesi alın ve MongoDB için Azure Cosmos DB'ye bağlanın.
using MongoDB.Driver;
var connectionString = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONNECTIONSTRING");
var client = new MongoClient(connectionString);
pom.xml dosyanıza aşağıdaki bağımlılığı ekleyin:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
Hizmet Bağlayıcısı tarafından eklenen ortam değişkeninden bağlantı dizesi alın ve MongoDB için Azure Cosmos DB'ye bağlanın.
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
String connectionString = System.getenv("AZURE_COSMOS_CONNECTIONSTRING");
MongoClientURI uri = new MongoClientURI(connectionString);
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient(uri);
} finally {
if (mongoClient != null) {
mongoClient.close();
}
}
Install dependency.
pip install pymongo
Hizmet Bağlayıcısı tarafından eklenen ortam değişkeninden bağlantı dizesi alın ve MongoDB için Azure Cosmos DB'ye bağlanın.
import os
import pymongo
conn_str = os.environ.get("AZURE_COSMOS_CONNECTIONSTRING")
client = pymongo.MongoClient(conn_str)
- Install dependency.
go get go.mongodb.org/mongo-driver/mongo
- Hizmet Bağlayıcısı tarafından eklenen ortam değişkeninden bağlantı dizesi alın ve MongoDB için Azure Cosmos DB'ye bağlanın.
import (
"context"
"fmt"
"log"
"os"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
mongoDBConnectionString = os.Getenv("AZURE_COSMOS_CONNECTIONSTRING")
clientOptions := options.Client().ApplyURI(mongoDBConnectionString).SetDirect(true)
c, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatalf("unable to initialize connection %v", err)
}
err = c.Ping(ctx, nil)
if err != nil {
log.Fatalf("unable to connect %v", err)
}
- Install dependency.
npm install mongodb
- Hizmet Bağlayıcısı tarafından eklenen ortam değişkeninden bağlantı dizesi alın ve MongoDB için Azure Cosmos DB'ye bağlanın.
const { MongoClient, ObjectId } = require('mongodb');
const url = process.env.AZURE_COSMOS_CONNECTIONSTRING;
const client = new MongoClient(url);
Diğer diller için, MongoDB için Azure Cosmos DB'ye bağlanmak amacıyla, Hizmet Bağlayıcısı'nın ortam değişkenlerine ayarladığı MongoDB kaynak uç noktasını ve diğer özellikleri kullanabilirsiniz. Ortam değişkeni ayrıntıları için bkz . MongoDB için Azure Cosmos DB'yi Service Connector ile tümleştirme.
Service principal
Varsayılan ortam değişkeni adı |
Açıklama |
Örnek değer |
AZURE_COSMOS_LISTCONNECTIONSTRINGURL |
The URL to get the connection string |
https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-API-for-MongoDB-account>/listConnectionStrings?api-version=2021-04-15 |
AZURE_COSMOS_SCOPE |
Your managed identity scope |
https://management.azure.com/.default |
AZURE_COSMOS_CLIENTID |
İstemci kimliğiniz |
<client-ID> |
AZURE_COSMOS_CLIENTSECRET |
Your client secret |
<client-secret> |
AZURE_COSMOS_TENANTID |
Kiracı kimliğiniz |
<tenant-ID> |
AZURE_COSMOS_RESOURCEENDPOINT |
Kaynak uç noktanız |
https://<Azure-Cosmos-DB-API-for-MongoDB-account>.documents.azure.com:443/ |
Örnek kod
Hizmet sorumlusu kullanarak MongoDB için Azure Cosmos DB'ye bağlanmak için aşağıdaki adımlara ve koda bakın.
Bağımlılıkları yükleme
dotnet add package MongoDb.Driver
dotnet add package Azure.Identity
Azure.Identity istemci kitaplığını kullanarak yönetilen kimlik veya hizmet sorumlusu için erişim belirteci alın. Erişim belirtecini ve AZURE_COSMOS_LISTCONNECTIONSTRINGURL
kullanarak bağlantı dizesini alın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
using System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using MongoDB.Driver;
using Azure.Identity;
using System.Text.Json;
// you can retrieve the endpoint of the resource with the following env variable:
// Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT");
var listConnectionStringUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to 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 string[]{ scope }));
// Get the connection string.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
var response = await httpClient.PostAsync(new Uri(listConnectionStringUrl), null);
var responseBody = await response.Content.ReadAsStringAsync();
var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody);
var connectionString = connectionStrings["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
var client = new MongoClient(connectionString);
pom.xml dosyanıza aşağıdaki bağımlılıkları ekleyin:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
azure-identity
kullanarak yönetilen kimlik veya hizmet sorumlusu için bir erişim belirteci alın. Erişim belirtecini ve AZURE_COSMOS_LISTCONNECTIONSTRINGURL
kullanarak bağlantı dizesini alın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
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;
String endpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT");
String listConnectionStringUrl = System.getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system 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();
// Get the access token.
AccessToken accessToken = defaultCredential.getToken(new TokenRequestContext().addScopes(new String[]{ scope })).block();
String token = accessToken.getToken();
// Get the connection string.
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(listConnectionStringUrl))
.header("Authorization", "Bearer " + token)
.POST()
.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 mongoClient = new MongoClient(uri);
Kimlik doğrulama türü Spring Boot için desteklenmiyor.
Bağımlılıkları yükleyin.
pip install pymongo
pip install azure-identity
Kodda, azure-identity
aracılığıyla erişim belirtecini alın ve bağlantı dizesini almak için kullanın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import os
import pymongo
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
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)
Bağımlılıkları yükleyin.
go get go.mongodb.org/mongo-driver/mongo
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
Kodda, azidentity
aracılığıyla erişim belirtecini alın ve bağlantı dizesini almak için kullanın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
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 identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// tenantid := os.Getenv("AZURE_COSMOS_TENANTID")
// clientsecret := os.Getenv("AZURE_COSMOS_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
// Acquire the access token.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{scope},
})
// Acquire the connection string.
client := &http.Client{}
req, err := http.NewRequest("POST", listConnectionStringUrl, nil)
req.Header.Add("Authorization", "Bearer " + token.Token)
resp, err := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
connectionString, err := result["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
clientOptions := options.Client().ApplyURI(connectionString).SetDirect(true)
c, err := mongo.Connect(ctx, clientOptions)
Bağımlılıkları yükleme
npm install mongodb
npm install --save @azure/identity
Kodda @azure/identity
aracılığıyla erişim belirtecini alın ve onu bağlantı dizisini almak için kullanın. Hizmet Bağlayıcısı tarafından eklenen ortam değişkenlerinden bağlantı bilgilerini alın ve MongoDB için Azure Cosmos DB'ye bağlanın. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const { MongoClient, ObjectId } = require('mongodb');
const axios = require('axios');
let endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT;
let listConnectionStringUrl = process.env.AZURE_COSMOS_LISTCONNECTIONSTRINGURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned 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;
// Acquire the access token.
var 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'];
const client = new MongoClient(connectionString);
Diğer diller için, MongoDB için Azure Cosmos DB'ye bağlanmak amacıyla, Hizmet Bağlayıcısı'nın ortam değişkenlerine ayarladığı MongoDB kaynak uç noktasını ve diğer özellikleri kullanabilirsiniz. Ortam değişkeni ayrıntıları için bkz . MongoDB için Azure Cosmos DB'yi Service Connector ile tümleştirme.
Sonraki adımlar
Service Connector hakkında daha fazla bilgi edinmek için aşağıda listelenen öğreticileri izleyin.