演習 - Azure Cosmos DB for MongoDB を使用して MongoDB DB アプリを作成する

完了

次は、プログラムで Azure Cosmos DB for MongoDB のデータベースとコレクションを作成し、いくつかのデータを追加する方法を確認します。

この演習は、一時的な Azure サブスクリプションを提供する Microsoft Learn の "サンドボックス" を使用して行うことができます。 サンドボックスのサブスクリプションをアクティブ化するには、Microsoft アカウントを使用してサインインする必要があります。 このモジュールを完了すると、サンドボックスのサブスクリプションは自動的に削除されます。 サンドボックスがアクティブ化されたら、 サンドボックス サブスクリプションの資格情報を使用して Azure portal にサインインします。 ポータルの右上にあるユーザー ID の下に示されている Microsoft Learn サンドボックス ディレクトリで作業していることを確認します。 そうでない場合は、ユーザー アイコンを選択してディレクトリを切り替えます。

ヒント

その方がよければ、自分の Azure サブスクリプションを使用してもかまいません。 これを行うには、 サブスクリプションの資格情報を使用して Azure portal にサインインします。 サブスクリプションが含まれているディレクトリで作業していることを確認してください。右上のユーザー ID の下に示されています。 そうでない場合は、ユーザー アイコンを選択してディレクトリを切り替えます。

Azure Cosmos DB for MongoDB Node.js 使用して MongoDB アプリを作成する

Java Azure Cosmos DB for MongoDB を使用して MongoDB アプリを作成する

Python Azure Cosmos DB for MongoDB を使用して MongoDB アプリを作成する

MongoDB 用 C# Azure Cosmos DB を使用して MongoDB アプリを作成する

この演習では、Azure Cosmos DB for MongoDB アカウント、データベース、コレクションを作成し、いくつかのドキュメントをコレクションに追加します。 このコードは、任意の MongoDB データベースに接続する方法と同じであることがわかります。 次に、コレクションの 1 秒あたりの要求ユニット数 (RU) でスループットを定義できる拡張コマンドを使用してコレクションを作成します。

開発環境を準備する

このラボで作業するための Azure Cosmos DB アカウントと環境をまだ準備していない場合は、次の手順に従って準備します。 それ以外の場合は、データベース 、コレクション、ドキュメントを作成するコードを App.js ファイル セクションに追加する に移動します。

このラボで作業するための環境と Azure Cosmos DB アカウントをまだ準備していない場合は、次の手順に従って準備します。 それ以外の場合は、「 コードを追加してデータベース、コレクション、ドキュメントを作成するApp.javaファイル 」セクションに移動します。

このラボで作業するための Azure Cosmos DB アカウントと環境をまだ準備していない場合は、次の手順に従って準備します。 それ以外の場合は、「 コードを追加してデータベース、コレクション、ドキュメントを作成する App.py ファイル 」セクションに移動します。

このラボで作業するための環境と Azure Cosmos DB アカウントをまだ準備していない場合は、次の手順に従って準備します。 それ以外の場合は、データベース 、コレクション、ドキュメントを作成するコードを app.cs ファイル セクションに追加する に移動します。

  1. Azure Cloud Shell で、次のコマンドをコピーして貼り付けます。

    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
    

    ヒント

    ラボにサンドボックスを使用していない場合に、データベース オブジェクトとストレージ オブジェクトを作成する場所を指定する場合は、init.sh 呼び出しに -l LOCATIONNAME パラメーターを追加します。 さらに、リソース グループを指定する場合は、init.sh 呼び出しに -r YOURRRESOURCEGROUPNAMEHERE パラメーターを追加します。

    この bash スクリプトでは、Azure Cosmos DB for MongoDB アカウントを作成します。 "このアカウントの作成には、5 から 10 分かかる場合がある" ため、コーヒー ブレイクにちょうどよい時間です。

    ヒント

    戻ってきて、Cloud Shell がリセットされている場合は、Cloud Shell で次のコマンドを実行して Node バージョン 14 を使用します。そうしなければ、次のセクションのコードは失敗します。

    1. source ~/.nvm/nvm.sh
    2. nvm install 14.0.0
    3. npm link mongodb
  2. bash init.sh ファイルの実行が完了したら、 接続文字列Cosmos DB アカウント名、および リソース グループ名 が返された場所にコピーします。次のセクションで必要になります。 また、接続文字列の前にあるアカウント作成スクリプトから返される JSON を確認することもできます。 JSON の途中のどこかを見ると、プロパティ "kind": "MongoDB" が表示されます。

    接続文字列Cosmos DB アカウント名リソース グループ名も Azure portal を使用して見つけることができます。

データベース、コレクションを作成し、ドキュメントを追加するコードを App.js ファイルに追加する

次に、データベース、コレクションを作成して、ドキュメントをコレクションに追加する JavaScript コードを追加します。

データベース、コレクションを作成し、ドキュメントを追加するコードを App.java ファイルに追加する

次に、データベース、コレクションを作成して、ドキュメントをコレクションに追加する Java コードを追加します。

データベース、コレクションを作成し、ドキュメントを追加するコードを App.py ファイルに追加する

次に、データベース、コレクションを作成して、ドキュメントをコレクションに追加する Python コードを追加します。

データベース、コレクションを作成し、ドキュメントを追加するコードを app.cs ファイルに追加する

次に、データベース、コレクションを作成して、ドキュメントをコレクションに追加する C# コードを追加します。

  1. まだ開いていない場合は、Azure Cloud Shell を開きます。

  2. 次のコマンドを実行して、コード エディターを開きます。

    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. 次のコードをアプリ ファイルにコピーします。 "前のセクションでコピーした接続文字列の URI の値を置き換える必要があることを忘れないでください"。

    コードのこの部分では、MongoDB ドライバーを使用します。また、通常 MongoDB サーバーへの接続文字列を使用する場合と同様に、Azure Cosmos DB への接続文字列を使用します。 コードでは、その後、Azure Cosmos DB アカウントへの接続を定義して開きます。

    // Uses the MongoDB driver
    const {MongoClient} = require("mongodb");
    
    async function main() {
    
        // One of the values you copied earlier was the connection string, replace it in the following line 
        var url = "TheConnectionStringYouCopiedEarlier";
    
        // define the connection using the MongoClient method ane the url above
        var mongoClient = new MongoClient(url, function(err,client)
        {
            if (err)
            {
                console.log("error connecting")
            }
        }
        );
    
        // open the connection
        await mongoClient.connect();
    
    
    package com.fabrikam;
    
    // Uses the MongoDB driver
    import com.mongodb.MongoClient;
    import com.mongodb.MongoClientURI;
    import com.mongodb.client.MongoDatabase;
    import com.mongodb.client.MongoCollection;
    import org.bson.Document;
    import static com.mongodb.client.model.Filters.eq;
    
    public class App {
        public static void main(String[] args) {
    
            // One of the values you copied earlier was the connection string, replace it in the following line 
            MongoClientURI uri = new MongoClientURI("TheConnectionStringYouCopiedEarlier");
    
            MongoClient mongoClient = null;
            try {
                // define the connection using the MongoClient method ane the url above and open the connection 
                mongoClient = new MongoClient(uri);
    
    
    # Use the MongoDB drivers
    import pymongo
    
    
    def main():
        # One of the values you copied earlier was the connection string, replace it in the following line 
        uri = "TheConnectionStringYouCopiedEarlier"
    
        # We use the "MongoClient" method and the "uri" value to connect to the account 
        client = pymongo.MongoClient(uri)
    
        ```
    
    
    // Uses the MongoDB driver
    using MongoDB.Driver;
    using MongoDB.Bson;
    using System;
    
    public class Products {
        public ObjectId Id { get; set; }  
        public int ProductId { get; set; }
        public string name { get; set; }
    }
    
    class App {
        public static void Main (string[] args) {
    
        // One of the values you copied earlier was the connection string, replace it in the following line 
        string connectionString = 
            @"TheConnectionStringYouCopiedEarlier";
    
        MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
    
        // define the connection using the MongoClient method ane the connectionString above and open the connection 
        var mongoClient = new MongoClient(settings);
    
    
  4. 次の手順では、 製品 データベースに接続します。 このデータベースが存在しない場合、データベースは、同じ接続でコレクションも作成する場合のみ、または拡張コマンドを使用してのみ作成されます。 エディターで次のコードをスクリプトに追加します。

    // 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. 次に、既に存在する場合は ドキュメント コレクションに接続し、1 つのドキュメントをコレクションに追加します。 このコレクションが存在しない場合、このコードは、同じ接続でそのコレクションに対して操作 (たとえば、コレクションにドキュメントを追加するなど) も実行する場合、または拡張コマンドを使用して、コレクションを作成します。 エディターで次のコードをスクリプトに追加します。

    
      // 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. 次は、挿入したドキュメントを検索し、シェルに表示します。 エディターで次のコードをスクリプトに追加します。

      // 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. 最後に、接続を閉じます。 エディターで次のコードをスクリプトに追加します。

      // 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. スクリプトは次のようになります。

    // 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. 次に進み、ここでプログラムを保存しましょう。 コード エディターの右上隅を選択し、[ 保存] (または Ctrl + S) を選択します。 次に、[ エディターを閉じる] (または Ctrl + Q) を選択してシェルに戻ります。

  10. ここで、次のコマンドを使用してアプリを実行してみましょう。

    node App.js
    
    mvn clean compile exec:java
    
    python App.py
    
    dotnet run
    
  11. このスクリプトでは、次のような結果が返されるはずです。 これは、データベース、コレクションが作成され、それにドキュメントが追加されたことを意味します。

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

お気付きのように、このコードは、MongoDB データベースでデータベース、コレクション、ドキュメントを作成するために実行するコードと同じです。 そのため、MongoDB に接続するアプリの作成に既に慣れている場合は、Azure Cosmos DB for MongoDB のプログラミングは透過的である必要があります。

マネージド ID

運用環境のワークロードでは、マネージド ID を使用して Azure Cosmos DB に対する認証を行うことをお勧めします。 この方法では、接続文字列を自分のコードに格納する必要はありません。 この次のセクションでは、マネージド ID を使用して Azure Cosmos DB に対する認証を行います。

運用環境では、必要最小限の特権でマネージド ID を使用する必要があります。 ユーザー割り当てマネージド ID は、1 つ以上作成し、Azure Cosmos DB アカウントに割り当てられます。 このラボでは、Azure Cosmos DB アカウントのシステム割り当てマネージド ID を作成します。

  1. Azure portal で、前に作成した Azure Cosmos DB アカウントに移動します。
  2. 左側のメニューの [設定] で 、[ ID] を選択します。
  3. [Identity] ペインで、[システム割り当て] を選択します。
  4. ステータスオン を選択します。
  5. [保存] を選択します
  6. マネージド ID が作成されるまでに 1 分から 2 分かかります。

マネージド ID が作成されたら、マネージド ID に必要なアクセス許可を Azure Cosmos DB アカウントに割り当てる必要があります。 今度は、RBAC (ロールベースのアクセス制御) を使用して、マネージド ID に必要なアクセス許可を割り当てます。 このラボでは、 共同作成者 ロールをマネージド ID に割り当てて、Azure Cosmos DB アカウントへのデータの読み取りと書き込みを許可します。 運用環境では、特権ロールは必要最小限に割り当てる必要があります。

  1. Azure portal で、前に作成した Azure Cosmos DB アカウントに移動します。
  2. 左側のメニューの [設定] で、[ アクセス制御 (IAM)] を選択します。
  3. [ + 追加] を選択し、[ ロールの割り当ての追加] を選択します。
  4. 特権管理者ロールで、[共同作成者] を選択し、[次へ] を選択します。
  5. [ メンバー] で [ マネージド ID] を選択し、[ + メンバーの選択] を選択します
  6. [ マネージド ID の選択 ] ウィンドウで、先ほど作成したマネージド ID を検索して選択し、[ 確認と割り当て] を選択します。

これで、必要なアクセス許可を持ち、Azure Cosmos DB アカウントに割り当てられたマネージド ID ができました。 次に、このマネージド ID を使用して、Azure Cosmos DB アカウントに対する認証を行います。

拡張コマンドを使用して、Azure Cosmos DB の MongoDB 用 API に格納されているデータを管理する

前のコードは、MongoDB サーバーに接続してから Azure Cosmos DB for MongoDB アカウントに接続する場合と同じですが、この接続は、Azure Cosmos DB 機能を利用できない可能性があります。 つまり、既定のドライバー メソッドを使用してコレクションを作成しますが、これらのコレクションの作成には既定の Azure Cosmos DB アカウント パラメーターも使用します。 そのため、それらのメソッドを使用して、スループット、シャーディング キー、または自動スケール設定などの作成パラメーターを定義することはできません。

Azure Cosmos DB for MongoDB の API を使用すると、Cosmos DB の利点を利用できます。 これらの利点には、グローバル分散、自動シャーディング、高可用性、待機時間の保証、自動化、保存時の暗号化、バックアップなどがあります。 さらに、MongoDB アプリへの投資を維持する利点も追加されました。 Azure Cosmos DB の MongoDB 用 API との通信は、オープンソースで公開されている任意の MongoDB クライアント ドライバーを使って行うことができます。 Azure Cosmos DB の MongoDB 用 API では、MongoDB ワイヤ プロトコルに従うことにより、既存のクライアント ドライバーを利用できます。

では、コレクションを作成し、そのシャーディング キーとスループットを定義できるコードを作成することにしましょう。

  1. まだ開いていない場合は、Azure Cloud Shell を開きます。

  2. 次のコマンドを実行して、コード エディターを開きます。

    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. 次のコードをファイルにコピーします。

    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. 次の手順では、 従業員 データベースに接続します。 このデータベースが存在しない場合、データベースは、同じ接続でコレクションも作成する場合のみ、または拡張コマンドを使用してのみ作成されます。 エディターで次のコードをスクリプトに追加します。

      // 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. これまでのところ、前のセクションのコードと同じように見えます。 この手順では、拡張コマンドを利用してカスタム アクションを作成します。 このアクションにより、コレクションのスループットとシャーディング キーを定義できます。 この手順では、コレクションの作成時に使用するパラメーターが、Azure Cosmos DB に提供されます。 エディターで次のコードをスクリプトに追加します。

      // 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. それ以外は前の例と同じです。 それでは、コレクションに接続し、何行か挿入し、最後にクエリを実行して行を出力してみます。 エディターで次のコードをスクリプトに追加します。

      // 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. スクリプトは次のようになります。

    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. 次に進み、ここでプログラムを保存しましょう。 コード エディターの右上隅を選択し、[ 保存] (または Ctrl + S) を選択します。 次に、[ エディターを閉じる] (または Ctrl + Q) を選択してシェルに戻ります。

  9. ここで、次のコマンドを使用してアプリを実行してみましょう。

    node App.js
    
    mvn clean compile exec:java
    
    python App.py
    
    dotnet run
    
  10. これにより、次のような結果が返されます。 これは、データベース、コレクションが作成され、それにドキュメントが追加されたことを意味します。

    {
      _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. しかし、この最後の結果セットは、実際にデータベース、コレクション、ドキュメントが作成されたことを確認しただけですが、シャード キーとスループットについてはどうでしょうか? 本当に変更されたでしょうか? Cloud Shell で、次のコマンドを実行して、変更が有効になったことを確認しましょう。

    1. シャード キーが EmployeeId (既定値は ID) に変更されたことを確認しましょう。 このラボの最初に保存したリソース グループ名アカウント名を忘れずに変更してください。

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

      結果には、プロパティ "shardKey": {"EmployeeId": "Hash"} が含まれている必要があります。

    2. スループットが 1000 (既定値は 400) に変更されたことを確認しましょう。 このラボの最初に保存したリソース グループ名アカウント名を忘れずに変更してください。

      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
      

      結果には、プロパティ "throughput": 1000 が含まれている必要があります。

このコードでは、コードで拡張コマンドを使用する機能を示しました。これにより、Azure Cosmos DB 作成パラメーターを定義できます。 これにより、Azure Cosmos DB でコレクションを作成して処理する方法を制御できます。

この演習を完了したら、このモジュールの知識チェックの質問に進んでください。