Alıştırma - MongoDB için Azure Cosmos DB kullanarak MongoDB DB uygulaması oluşturma

Tamamlandı

MongoDB veritabanları, koleksiyonları ve bazı veriler eklemek için Azure Cosmos DB'mizin nasıl oluşturulacağını program aracılığıyla gözden geçirmenin zamanı geldi.

Bu alıştırma, geçici bir Azure aboneliği sağlayan bir Microsoft Learn sandbox kullanılarak tamamlanabilir. Korumalı alan aboneliğini etkinleştirmek için bir Microsoft hesabı kullanarak oturum açmanız gerekir. Bu modülü tamamladığınızda korumalı alan aboneliği otomatik olarak silinir. Korumalı alan etkinleştirildikten sonra korumalı alan aboneliğinizin kimlik bilgilerini kullanarak Azure portalında oturum açın. Portalın sağ üst kısmında kullanıcı kimliğiniz altında gösterilen Microsoft Learn Korumalı Alan dizininde çalıştığınızdan emin olun. Aksi takdirde, kullanıcı simgesini seçin ve dizini değiştirin.

İpucu

İsterseniz kendi Azure aboneliğinizi kullanabilirsiniz. Bunu yapmak için aboneliğinizin kimlik bilgilerini kullanarak Azure portalında oturum açın. Kullanıcı kimliğinizin sağ üst kısmında belirtilen aboneliğinizi içeren dizinde çalıştığınızdan emin olun. Aksi takdirde, kullanıcı simgesini seçin ve dizini değiştirin.

MongoDB için Azure Cosmos DB 'Node.js kullanarak MongoDB uygulaması oluşturma

MongoDB için Java Azure Cosmos DB kullanarak MongoDB uygulaması oluşturma

MongoDB için Python Azure Cosmos DB kullanarak MongoDB uygulaması oluşturma

MongoDB için C# Azure Cosmos DB kullanarak MongoDB uygulaması oluşturma

Bu alıştırmada MongoDB için Azure Cosmos DB hesabı, veritabanı, koleksiyon oluşturacak ve koleksiyona birkaç belge ekleyebilirsiniz. Bu kodun herhangi bir MongoDB veritabanına nasıl bağlanacağınızla aynı olduğunu fark ediyorsunuz. Ardından, koleksiyon için İstek Birimleri/sn (RU) cinsinden aktarım hızını tanımlamanıza olanak sağlayan uzantı komutlarını kullanarak bir koleksiyon oluşturursunuz.

Geliştirme ortamınızı hazırlama

Bu laboratuvar üzerinde çalıştığınız Azure Cosmos DB hesabınız ve ortamınız yoksa, bunu yapmak için aşağıdaki adımları izleyin. Aksi takdirde, veritabanlarını, koleksiyonu ve belgeyi oluşturmak için kodu App.js dosyasına ekleme bölümüne gidin.

Bu laboratuvar üzerinde çalıştığınız ortamı ve Azure Cosmos DB hesabını kullanmıyorsanız, bunu yapmak için aşağıdaki adımları izleyin. Aksi takdirde, veritabanlarını, koleksiyonu ve belgeyi oluşturmak için kod ekleme kısmı olan App.java dosyasına gidin.

Bu laboratuvar üzerinde çalıştığınız Azure Cosmos DB hesabını ve ortamını kullanmıyorsanız, bunu yapmak için aşağıdaki adımları izleyin. Aksi takdirde, veritabanlarını, koleksiyonu ve belgeyi oluşturmak için gerekli kodu App.py dosyasına ekleyin bölümüne gidin.

Bu laboratuvar üzerinde çalıştığınız ortamınız ve Azure Cosmos DB hesabınız yoksa, bunu yapmak için aşağıdaki adımları izleyin. Aksi takdirde, veritabanlarını, koleksiyonu ve belgeyi oluşturmak için kodu app.cs dosyasına ekleyin bölümüne gidin.

  1. Azure Cloud Shell'de aşağıdaki komutları kopyalayıp yapıştırın.

    git clone https://github.com/MicrosoftLearning/mslearn-cosmosdb.git
    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/node/
    
    # Update Azure Cloud Shell node to Version 14.0.0, since the MongoDB driver requires ver 10+
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
    source ~/.nvm/nvm.sh
    nvm install 14.0.0
    npm install -g mongodb
    npm link mongodb
    # Check if the node version is now v14.0.0
    node --version
    
    # Create an Azure Cosmos DB for MongoDB account
    bash ../init.sh
    
    git clone https://github.com/MicrosoftLearning/mslearn-cosmosdb.git
    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/java
    # Download and install the Maven project, this will take a minute or two
    mvn archetype:generate -DgroupId=com.fabrikam -DartifactId=AzureApp -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    # Replace the projects pom.xml file with the github one that has the MongoDB definition
    mv pom.xml1 ./AzureApp/pom.xml
    
    # Create an Azure Cosmos DB for MongoDB account
    bash ../init.sh
    
    git clone https://github.com/MicrosoftLearning/mslearn-cosmosdb.git
    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/python
    # Install the MongoDB Python drivers
    python -m pip install pymongo
    # Create an Azure Cosmos DB for MongoDB account
    bash ../init.sh
    
    git clone https://github.com/MicrosoftLearning/mslearn-cosmosdb.git
    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/csharp
    
    # Add MongoDB driver to DotNet
    dotnet add package MongoDB.Driver --version 2.16.0
    
    # Create an Azure Cosmos DB for MongoDB account
    bash ../init.sh
    

    İpucu

    Laboratuvar için korumalı alanı kullanmıyorsanız ve veritabanınızı ve depolama nesnelerinizi oluşturmak istediğiniz konumu belirtmek istiyorsanız, init.sh çağrısına bir -l LOCATIONNAME parametresi ekleyin. Ayrıca, bir kaynak grubu belirtmek isterseniz, init.sh çağrısına bir -r YOURRRESOURCEGROUPNAMEHERE parametresi ekleyin.

    Not

    Bu bash betiği MongoDB için Azure Cosmos DB hesabını oluşturur. Bu hesabı oluşturmak 5-10 dakika sürebilir , bu nedenle bir fincan kahve veya çay almak için iyi bir zaman olabilir.

    İpucu

    Geri dönerseniz ve cloud shell'iniz sıfırlanırsa, Cloud Shell'de aşağıdaki komutları çalıştırarak Node sürüm 14'i kullanın; aksi takdirde sonraki bölümdeki kod başarısız olur.

    1. kaynak ~/.nvm/nvm.sh
    2. nvm yükleme 14.0.0
    3. npm link mongodb
  2. Bash init.sh dosyasının çalışması tamamlandığında Bağlantı Dizesi, Cosmos DB Hesap adı ve Döndürülen Kaynak Grubu adı değerlerini bir yere kopyalayın. Sonraki bölümde bunlara ihtiyacımız olacak. Ayrıca, bağlantı dizesi önce bulunan hesap oluşturma betiği tarafından döndürülen JSON'yi de gözden geçirebilirsiniz. JSON'un ortasında bir yere bakarsanız "kind": "MongoDB" özelliğini görmeniz gerekir.

    Not

    Bağlantı Dizesi, Cosmos DB Hesap adı ve Kaynak Grubu adının Azure portalı kullanılarak da bulunabileceğini unutmayın.

Veritabanlarını, koleksiyonu ve belgeyi oluşturmak için kodu App.js dosyasına ekleyin

Şimdi Veritabanı, Koleksiyon oluşturmak ve koleksiyona belge eklemek için JavaScript kodumuzu eklemenin zamanı geldi.

Veritabanlarını, koleksiyonu ve belgeyi oluşturmak için kodu App.java dosyasına ekleyin

Şimdi Veritabanı, Koleksiyon oluşturmak ve koleksiyona belge eklemek için Java kodumuzu eklemenin zamanı geldi.

Veritabanlarını, koleksiyonu ve belgeyi oluşturmak için kodu App.py dosyasına ekleyin

Şimdi Bir Veritabanı, Koleksiyon oluşturmak ve koleksiyona bir belge eklemek için Python kodumuzu eklemenin zamanı geldi.

Veritabanlarını, koleksiyonları ve belgeyi oluşturmak için kodu app.cs dosyasına ekleyin

Şimdi C# kodumuzu ekleyerek Veritabanı, Koleksiyon oluşturma ve koleksiyona belge ekleme zamanı geldi.

  1. Henüz açılmamış bölümünde Azure Cloud Shell'i açın.

  2. Kod düzenleyicisini açmak için aşağıdaki komutu çalıştırın.

    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/node/
    code App.js
    
    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/java/AzureApp
    code ./src/main/java/com/fabrikam/App.java
    
    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/python
    code App.py
    
    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/csharp
    code app.cs
    
  3. Aşağıdaki kodu Uygulama dosyasına kopyalayın. Önceki bölümde kopyalanan bağlantı dizesi için uri değerini değiştirmeniz gerektiğini unutmayın.

    Kodun bu bölümü MongoDB sürücülerini kullanır ve normalde herhangi bir MongoDB sunucusuna bağlantı dizesi kullandığınız gibi Azure Cosmos DB'ye bağlantı dizesi kullanır. Kod daha sonra Azure Cosmos DB hesabı bağlantısını tanımlar ve açar.

    // 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);
    
    
  4. Sonraki adım ürünler veritabanına bağlanır. Bu veritabanı yoksa, yalnızca aynı bağlantıda veya uzantı komutlarını kullanarak bir koleksiyon da oluşturduğunda bunu oluşturur. Aşağıdakini düzenleyicideki betike ekleyin.

    // 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");
    
    
  5. Daha sonra, zaten varsa belgeler koleksiyonuna bağlanacak ve ardından koleksiyona bir belge ekleyeceğiz. Koleksiyon yoksa bu kod, aynı bağlantıda (örneğin, koleksiyona belge ekleme gibi) veya uzantı komutlarını kullanarak bu koleksiyon üzerinde bir işlem gerçekleştiriyorsa koleksiyonu oluşturur. Aşağıdakini düzenleyicideki betike ekleyin.

    
      // 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);
    
    
  6. Şimdi eklenen belgeyi ara ve kabukta görüntüle. Aşağıdakini düzenleyicideki betike ekleyin.

      // 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);
      }
    }
    
  7. Son olarak bağlantıyı kapatalım. Aşağıdakini düzenleyicideki betike ekleyin.

      // 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.
    
  8. Betik şu şekilde görünmelidir:

    // 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);
      }
    }
    
  9. Haydi programı kaydedelim. Kod düzenleyicisinin sağ üst köşesinden Kaydet'i (veya Ctrl+S) seçin. Şimdi Shell'e geri dönmek için Düzenleyiciyi Kapat'ı (veya Ctrl+Q) seçin.

  10. Şimdi uygulamayı aşağıdaki komutla çalıştıralım.

    node App.js
    
    mvn clean compile exec:java
    
    python App.py
    
    dotnet run
    
  11. Bu betik aşağıdakine benzer bir sonuç döndürmelidir. Bu, veritabanını, koleksiyonu oluşturduğumuz ve buna bir belge eklediğimiz anlamına gelir.

    {
      _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'
    

Fark edeceğiniz gibi, bu kod MongoDB veritabanında veritabanı, koleksiyon ve belge oluşturmak için çalıştıracağınız kodla aynıdır. Bu nedenle MongoDB için Azure Cosmos DB programlama, MongoDB'ye bağlanan uygulamalar oluşturmayı zaten biliyorsanız sizin için şeffaf olmalıdır.

Yönetilen kimlikler

Üretim iş yükleri için Azure Cosmos DB'de kimlik doğrulaması yapmak için yönetilen kimlikleri kullanmanızı öneririz. Bu şekilde, bağlantı dizesi kodunuzda depolamanız gerekmez. Sonraki bölümde Azure Cosmos DB'de kimlik doğrulaması yapmak için yönetilen kimlikleri kullanacağız.

Bir üretim ortamında, gerekli en az ayrıcalığı olan bir yönetilen kimlik kullanmalısınız. Kullanıcı tarafından atanan bir veya daha fazla yönetilen kimlik oluşturabilir ve bunları Azure Cosmos DB hesabına atayabilirsiniz. Bu laboratuvar için Azure Cosmos DB hesabı için sistem tarafından atanan bir yönetilen kimlik oluşturalım.

  1. Azure portalında, daha önce oluşturduğunuz Azure Cosmos DB hesabına gidin.
  2. Sol taraftaki menüde , Ayarlar'ın altında Kimlik'i seçin.
  3. Kimlik bölmesinde Sistem Atanmış'ı seçin.
  4. Durum için Açık seçeneğini seçin.
  5. Kaydet'i seçin.
  6. Yönetilen kimliğin oluşturulması bir veya iki dakika sürer.

Yönetilen kimlik oluşturulduktan sonra yönetilen kimliği Azure Cosmos DB hesabına gerekli izinleri atamamız gerekir. Yönetilen kimliğe gerekli izinleri atamak için RBAC 'yi (Rol Tabanlı Erişim Denetimi) kullanma zamanı. Bu laboratuvarda, Azure Cosmos DB hesabına veri okumasına ve yazmasına izin vermek için yönetilen kimliğe Katkıda Bulunan rolünü atarız. Üretim ortamında, gerekli en düşük ayrıcalık rolünü atamanız gerekir.

  1. Azure portalında, daha önce oluşturduğunuz Azure Cosmos DB hesabına gidin.
  2. Sol taraftaki menüde , Ayarlar'ın altında Erişim denetimi (IAM) öğesini seçin.
  3. + Ekle'yi ve ardından Rol ataması ekle'yi seçin.
  4. Ayrıcalıklı yönetici rolü altında Katkıda Bulunan'ı ve İleri'yi seçin.
  5. Üyeler'in altında Yönetilen Kimlik'i ve ardından + Üyeleri seçin'i seçin.
  6. Yönetilen kimlikleri seçin penceresinde, daha önce oluşturduğunuz yönetilen kimliği arayın, seçin ve ardından Gözden Geçir ve Ata seçeneğini seçin.

Artık Azure Cosmos DB hesabına gerekli izinlerle atanmış bir yönetilen kimliğiniz var. Şimdi Azure Cosmos DB hesabında kimlik doğrulaması yapmak için yönetilen kimliği kullanalım.

MongoDB için Azure Cosmos DB API'sinde depolanan verileri yönetmek için uzantı komutlarını kullanma

Önceki kod, mongoDB sunucusuna bağlanıp MongoDB için Azure Cosmos DB hesabımızla bağlantı kurmak arasında aynı olsa da, bağlantı Azure Cosmos DB özelliklerinden yararlanamayabilir. Bunun anlamı, koleksiyonlarımızı oluşturmak için varsayılan sürücü yöntemlerini kullanmak ve bu koleksiyonları oluşturmak için varsayılan Azure Cosmos DB Hesabı parametrelerini kullanmaktır. Bu nedenle bu yöntemleri kullanarak aktarım hızımız, parçalama anahtarımız veya otomatik ölçeklendirme ayarlarımız gibi oluşturma parametrelerini tanımlayamıyoruz.

MongoDB için Azure Cosmos DB API'sini kullanarak Cosmos DB'nin avantajlarından yararlanabilirsiniz. Bu avantajlar arasında genel dağıtım, otomatik parçalama, yüksek kullanılabilirlik, gecikme süresi garantileri, otomatik, bekleyen şifreleme, yedeklemeler ve daha birçok avantaj yer alır. Ayrıca MongoDB uygulamanıza yatırımlarınızı korumanın ek avantajı. Açık kaynak MongoDB istemci sürücülerinden herhangi birini kullanarak MongoDB için Azure Cosmos DB API'si ile iletişim kurabilirsiniz. MongoDB için Azure Cosmos DB API'si, MongoDB kablo protokolüne bağlı olarak mevcut istemci sürücülerinin kullanılmasını sağlar.

Şimdi bir koleksiyon oluşturmamıza ve parçalama anahtarını ve aktarım hızını tanımlamamıza olanak tanıyan bazı kodlar oluşturalım.

  1. Henüz açılmamış bölümünde Azure Cloud Shell'i açın.

  2. Kod düzenleyicisini açmak için aşağıdaki komutu çalıştırın.

    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/node
    code App.js
    
    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/java/AzureApp
    code ./src/main/java/com/fabrikam/App.java
    
    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/python
    code App.py
    
    cd ~/mslearn-cosmosdb/api-for-mongodb/01-create-mongodb-objects/csharp
    code app.cs
    
  3. Aşağıdaki kodu dosyaya kopyalayın.

    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);
    
    
  4. Sonraki adım çalışanlar veritabanına bağlanır. Bu veritabanı yoksa, yalnızca aynı bağlantıda veya uzantı komutlarını kullanarak bir koleksiyon da oluşturduğunda bunu oluşturur. Aşağıdakini düzenleyicideki betike ekleyin.

      // 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");
    
    
  5. Şimdiye kadar önceki bölümdeki koda çok benziyor. Bu adımda uzantı komutlarından yararlanacak ve özel bir eylem oluşturacağız. Bu eylem, işleme hızını ve koleksiyonun parçalama anahtarını tanımlamamıza olanak tanır. Buna karşılık adım, Azure Cosmos DB'ye koleksiyonu oluştururken kullanılacak parametreleri verir. Aşağıdakini düzenleyicideki betike ekleyin.

      // 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""}");
    
    
  6. Geri kalanı önceki örnekle aynıdır. Koleksiyona bağlanıyoruz, bazı satırlar ekliyoruz, son olarak bir satırı sorgulayıp çıkışını geri alıyoruz. Aşağıdakini düzenleyicideki betike ekleyin.

      // 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);
      }
    }
    
  7. Betik şu şekilde görünmelidir:

    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);
        }
    }
    
  8. Haydi programı kaydedelim. Kod düzenleyicisinin sağ üst köşesinden Kaydet'i (veya Ctrl+S) seçin. Şimdi Shell'e geri dönmek için Düzenleyiciyi Kapat'ı (veya Ctrl+Q) seçin.

  9. Şimdi uygulamayı aşağıdaki komutla çalıştıralım.

    node App.js
    
    mvn clean compile exec:java
    
    python App.py
    
    dotnet run
    
  10. Bu, aşağıdakine benzer bir sonuç döndürmelidir. Bu, veritabanını, koleksiyonu oluşturduğumuz ve buna bir belge eklediğimiz anlamına gelir.

    {
      _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'
    
  11. Ancak bu son sonuç kümesi yalnızca bir veritabanı, koleksiyon ve belgeler oluşturduğumuzu doğruladı, ancak parça anahtarımız ve aktarım hızımız gerçekten değişti mi? Cloud Shell'de, değişikliklerimizin etkili olduğunu doğrulamak için aşağıdaki komutları çalıştıralım.

    1. Şimdi, Shard anahtarımızın EmployeeId (varsayılan olarak id) şeklinde değiştiğini doğrulayalım. Bu laboratuvarın başında kaydettiğimiz adlar için kaynak grubu adını ve hesap adını değiştirmeyi unutmayın.

      az cosmosdb mongodb collection show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734
      

      Sonuç "shardKey" özelliğini içermelidir: {"EmployeeId": "Hash"}.

    2. Aktarım hızımızın 1000 olarak değiştiğini doğrulayalım (varsayılan değer 400'dür). Bu laboratuvarın başında kaydettiğimiz adlar için kaynak grubu adını ve hesap adını değiştirmeyi unutmayın.

      az cosmosdb mongodb collection throughput show --name Employee --database-name HumanResources --resource-group learn-20c8df29-1419-49f3-84bb-6613f052b5ae --account-name learn-account-cosmos-845083734
      

      Sonuç "aktarım hızı" özelliğini içermelidir: 1000.

Bu kod, Kodumuzda Azure Cosmos DB oluşturma parametrelerini tanımlamamıza olanak tanıyan genişletilmiş komutları kullanmanın gücünü göstermiş. Bu sayede koleksiyonlarımızın Azure Cosmos DB tarafından nasıl oluşturulacağını ve işlendiğini denetleme avantajından yararlanabiliriz.

Bu alıştırmayı tamamladıktan sonra bu modülle ilgili bilgi kontrolü sorularına devam edin.