연습 - Azure Cosmos DB for MongoDB를 사용하여 MongoDB의 DB 앱 만들기

완료됨

이제 Azure Cosmos DB for MongoDB 데이트베이스, 컬렉션을 만들고 일부 데이터를 추가하는 방법을 프로그래밍 방식으로 확인해야 합니다.

이 연습은 임시 Azure 구독을 제공하는 Microsoft Learn 샌드박스를 사용하여 진행할 수 있습니다. 샌드박스 구독을 활성화하려면 Microsoft 계정을 사용하여 로그인해야 합니다. 이 모듈을 마치면 샌드박스 구독이 자동으로 삭제됩니다. 샌드박스가 활성화되면 샌드박스 구독의 자격 증명을 사용하여 Azure Portal에 로그인합니다. 현재 Microsoft Learn 샌드박스 디렉터리에서 작업하고 있는지 확인합니다. 디렉터리는 포털 오른쪽 상단의 사용자 ID 아래에서 확인할 수 있습니다. 그렇지 않은 경우 사용자 아이콘을 선택하고 디렉터리를 전환합니다.

원한다면 사용자 자신의 Azure 구독을 사용해도 됩니다. 자체 Azure 구독을 사용하려면 구독의 자격 증명을 사용하여 Azure Portal에 로그인합니다. 현재 구독을 포함하는 디렉터리에서 작업하고 있는지 확인합니다. 디렉터리는 오른쪽 상단의 사용자 ID 아래에서 확인할 수 있습니다. 그렇지 않은 경우 사용자 아이콘을 선택하고 디렉터리를 전환합니다.

Node.js Azure Cosmos DB for MongoDB를 사용하여 MongoDB 앱 만들기

Java Azure Cosmos DB for MongoDB를 사용하여 MongoDB 앱 만들기

Python Azure Cosmos DB for MongoDB를 사용하여 MongoDB 앱 만들기

C# Azure Cosmos DB for MongoDB를 사용하여 MongoDB 앱 만들기

이 연습에서는 Azure Cosmos DB for MongoDB 계정, 데이터베이스, 컬렉션을 만들고 컬렉션에 몇 개의 문서를 추가합니다. 이 코드는 MongoDB 데이터베이스에 연결하는 방법과 동일합니다. 그런 다음, 컬렉션에 대한 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 매개 변수를 추가합니다. 또한 리소스 그룹을 지정하려면 -r YOURRRESOURCEGROUPNAMEHERE 매개 변수를 init.sh 호출에 추가합니다.

    참고

    이 bash 스크립트는 Azure Cosmos DB for MongoDB 계정을 만듭니다. 이 계정을 만드는 데 5~10분 정도 걸릴 수 있으므로 커피나 차 한 잔을 마시는 것이 좋습니다.

    돌아와서 클라우드 셸이 다시 설정되면 클라우드 셸에서 다음 명령을 실행하여 노드 버전 14를 사용합니다. 그렇지 않으면 다음 섹션의 코드가 실패합니다.

    1. source ~/.nvm/nvm.sh
    2. nvm 설치 14.0.0
    3. npm 링크 mongodb
  2. bash init.sh 파일 실행이 완료되면 연결 문자열, Cosmos DB 계정 이름리소스 그룹 이름이 반환된 위치를 복사합니다. 다음 섹션에서 필요합니다. 연결 문자열 앞에 있는 계정 만들기 스크립트에서 반환된 JSON을 검토할 수도 있습니다. JSON의 중간 위치를 보면 "kind": "MongoDB" 속성이 표시됩니다.

    참고

    Azure Portal을 사용하여 연결 문자열, Cosmos DB 계정 이름, 리소스 그룹 이름을 찾을 수도 있습니다.

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. 다음 코드를 앱 파일에 복사합니다. 이전 섹션에서 복사한 연결 문자열의 URL 값을 바꿔야 합니다.

    코드의 이 부분에서는 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. 다음으로, 문서 컬렉션이 이미 있는 경우 문서 컬렉션에 연결한 다음, 컬렉션에 하나의 문서를 추가합니다. 컬렉션이 없는 경우 이 코드는 동일한 연결(예: 컬렉션에 문서 추가 등)에서 또는 확장 명령을 사용하여 해당 컬렉션에 대한 작업을 수행하는 경우에도 컬렉션을 만듭니다. 편집기에서 스크립트에 다음을 추가합니다.

    
      // 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를 만들고 Azure Cosmos DB 계정에 할당할 수 있습니다. 이 랩의 경우 Azure Cosmos DB 계정에 대한 시스템 할당 관리 ID를 만들어 보겠습니다.

  1. Azure Portal에서 이전에 만든 Azure Cosmos DB 계정으로 이동합니다.
  2. 설정 아래 왼쪽 메뉴에서 ID를 선택합니다.
  3. ID 창에서 시스템 할당을 선택합니다.
  4. 상태에 대해 켜기를 선택합니다.
  5. 저장을 선택합니다.
  6. 관리 ID를 생성하는 데 1~2분 정도 소요됩니다.

관리 ID가 만들어지면 관리 ID에 Azure Cosmos DB 계정에 필요한 권한을 할당해야 합니다. RBAC(역할 기반 액세스 제어)를 사용하여 관리 ID에 필요한 권한을 할당할 시간입니다. 이 랩의 경우 Azure Cosmos DB 계정에 데이터를 읽고 쓸 수 있도록 관리 ID에 기여자 역할을 할당합니다. 프로덕션 환경에서 필요한 최소 권한 역할을 할당해야 합니다.

  1. Azure Portal에서 이전에 만든 Azure Cosmos DB 계정으로 이동합니다.
  2. 왼쪽 메뉴의 설정 아래에서 IAM(액세스 제어)을 선택합니다.
  3. + 추가, 역할 할당 추가를 차례로 선택합니다.
  4. 권한 있는 관리자 역할 아래에서 기여자를 선택하고 다음을 선택합니다.
  5. 멤버 아래에서 관리 ID를 선택한 다음, + 멤버 선택을 선택합니다.
  6. 관리 ID 선택 창에서 이전에 만든 관리 ID를 검색하고 선택한 다음, 검토 + 할당을 선택합니다.

이제 필요한 권한이 있는 관리 ID가 Azure Cosmos DB 계정에 할당되었습니다. 이제 관리 ID를 사용하여 Azure Cosmos DB 계정에서 인증을 받아 보겠습니다.

확장 명령을 사용하여 MongoDB용 Azure Cosmos DB의 API에 저장된 데이터 관리

이전 코드는 MongoDB 서버에 연결한 다음, Azure Cosmos DB for MongoDB 계정에 연결하는 경우 동일하지만 이렇게 연결하면 Azure Cosmos DB 기능을 활용하지 못할 수 있습니다. 즉, 기본 드라이버 메서드를 사용하여 컬렉션을 만들고 기본 Azure Cosmos DB 계정 매개 변수를 사용하여 해당 컬렉션을 만듭니다. 따라서 이러한 메서드를 사용하여 처리량, 분할 키 또는 자동 스케일링 설정과 같은 생성 매개 변수를 정의할 수 없습니다.

Azure Cosmos DB의 API for MongoDB를 사용하면 Cosmos DB의 이점을 누릴 수 있습니다. 이러한 이점에는 글로벌 배포, 자동 분할, 고가용성, 대기 시간 보장, 자동, 미사용 암호화, 백업 등이 있습니다. 또한 MongoDB 앱에 대한 투자를 보존한다는 추가적인 이점도 있습니다. 오픈 소스 MongoDB 클라이언트 드라이버를 사용하여 Azure Cosmos DB의 API for MongoDB와 통신할 수 있습니다. MongoDB용 Azure Cosmos DB의 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에서 컬렉션을 만들고 처리하는 방법을 제어할 수 있습니다.

이 연습을 완료했으면 이 모듈에 대한 지식 점검 질문을 계속 진행합니다.