Упражнение. Создание приложения базы данных MongoDB с помощью Azure Cosmos DB для MongoDB

Завершено

Пришло время программно узнать, как создать базы данных, коллекции и добавить некоторые данные в Azure Cosmos DB для MongoDB программным способом.

Это упражнение можно выполнить в песочнице Microsoft Learn, которая предоставляет временную подписку Azure. Чтобы активировать подписку из песочницы, необходимо выполнить вход с помощью учетной записи Майкрософт. Подписка песочницы автоматически удаляется при завершении этого модуля. После активации песочницы войдите в портал Azure с помощью учетных данных для подписки песочницы. Убедитесь, что вы работаете в каталоге Microsoft Learn Sandbox — он указан в правом верхнем углу портала под идентификатором пользователя. В противном случае нажмите значок пользователя и переключите каталог.

Совет

При желании вы можете использовать собственную подписку Azure. Для этого войдите на портал Azure с помощью учетных данных для своей подписки. Убедитесь, что вы работаете в каталоге, содержащем вашу подписку — он указан в правом верхнем углу под вашим идентификатором пользователя. В противном случае нажмите значок пользователя и переключите каталог.

Создание приложения MongoDB с помощью Node.js Azure Cosmos DB для MongoDB

Создание приложения MongoDB с помощью Java Azure Cosmos DB для MongoDB

Создание приложения MongoDB с помощью Python Azure Cosmos DB для MongoDB

Создание приложения MongoDB с помощью C# Azure Cosmos DB для MongoDB

В этом упражнении вы создадите учетную запись Azure Cosmos DB для MongoDB, базу данных, коллекцию и добавьте в коллекцию несколько документов. Обратите внимание, что этот код идентичен подключению к любой базе данных MongoDB. Затем вы создадите коллекцию с помощью команд расширения, которые позволяют определить пропускную способность в единицах запросов/с (ЕЗ) для коллекции.

Подготовка среды разработки

Если у вас нет учетной записи и среды 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
    

    Совет

    Если вы не используете песочницу для лаборатории и хотите указать расположение, в котором вы хотите создать базу данных и объекты хранилища, добавьте параметр -l LOCATIONNAME в вызов init.sh. Кроме того, если вы хотите указать группу ресурсов, добавьте параметр -r YOURRRESOURCEGROUPNAMEHERE в вызов init.sh .

    Примечание.

    Этот скрипт bash создаст учетную запись Azure Cosmos DB для 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.

Добавьте код для создания баз данных, коллекции и документа в файл App.js

Теперь пора добавить код JavaScript для создания базы данных, коллекции и добавления документа в коллекцию.

Добавьте код для создания баз данных, коллекции и документа в файл App.java

Теперь пора добавить код Java для создания базы данных, коллекции и добавления документа в коллекцию.

Добавьте код для создания баз данных, коллекции и документа в файл App.py

Теперь пора добавить код Python для создания базы данных, коллекции и добавления документа в коллекцию.

Добавьте код для создания баз данных, коллекции и документа в файл app.cs

Теперь пора добавить код C# для создания базы данных, коллекции и добавления документа в коллекцию.

  1. Откройте Cloud Shell Azure, если вы этого еще не сделали.

  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 и строка подключения к Azure Cosmos DB, например, для любого сервера MongoDB обычно используется строка подключения. Затем код определяет и открывает подключение к учетной записи 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. Следующий шаг подключается к базе данных products. Если эта база данных не существует, она создает ее только в том случае, если также создается коллекция в том же соединении или с помощью команд расширения. Добавьте следующий код в скрипт в редакторе.

    // 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), чтобы вернуться к Shell.

  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. Поэтому программирование для Azure Cosmos DB для MongoDB должно быть прозрачным для вас, если вы уже знакомы с созданием приложений, которые подключаются к MongoDB.

Управляемые удостоверения

Для рабочих нагрузок рекомендуется использовать управляемые удостоверения для проверки подлинности в Azure Cosmos DB. Таким образом, вам не нужно хранить строка подключения в коде. В этом разделе мы будем использовать управляемые удостоверения для проверки подлинности в Azure Cosmos DB.

В рабочей среде следует использовать управляемое удостоверение с минимальными привилегиями. Вы можете создать одно или несколько управляемых удостоверений, назначенных пользователем, и назначить их учетной записи Azure Cosmos DB. Для этой лаборатории давайте создадим управляемое удостоверение, назначаемое системой, для учетной записи Azure Cosmos DB.

  1. В портал Azure перейдите к созданной ранее учетной записи Azure Cosmos DB.
  2. В меню слева в разделе "Параметры" выберите "Удостоверение".
  3. В области удостоверений выберите "Назначенная система".
  4. Выберите "Вкл." для состояния.
  5. Выберите Сохранить.
  6. Создание управляемого удостоверения занимает одну или две минуты.

После создания управляемого удостоверения необходимо назначить управляемое удостоверение необходимым разрешениям учетной записи Azure Cosmos DB. Время использования RBAC (контроль доступа на основе ролей) для назначения управляемого удостоверения необходимым разрешениям. Для этой лаборатории мы назначаем роль участника управляемому удостоверению, чтобы разрешить ей читать и записывать данные в учетную запись Azure Cosmos DB. В рабочей среде необходимо назначить минимальную роль привилегий.

  1. В портал Azure перейдите к созданной ранее учетной записи Azure Cosmos DB.
  2. В меню слева в разделе "Параметры" выберите элемент управления доступом (IAM).
  3. Выберите +Добавить и добавьте назначение ролей.
  4. В разделе роли "Привилегированный администратор" выберите "Участник" и нажмите кнопку "Далее".
  5. В разделе "Члены" выберите управляемое удостоверение и нажмите кнопку "Выбрать".
  6. В области "Выбор управляемых удостоверений" найдите созданное ранее управляемое удостоверение, выберите его, а затем нажмите кнопку "Проверить и назначить".

Теперь у вас есть управляемое удостоверение, назначенное учетной записи Azure Cosmos DB с необходимыми разрешениями. Теперь используйте управляемое удостоверение для проверки подлинности в учетной записи Azure Cosmos DB.

Использование команд расширения для управления данными, хранящимися в API-интерфейсе Azure Cosmos DB для MongoDB

Хотя предыдущий код будет идентичен подключению к серверу MongoDB, а затем подключиться к нашей учетной записи Azure Cosmos DB для MongoDB, подключение может не воспользоваться функциями Azure Cosmos DB. Это означает, что для создания коллекций используются методы драйвера по умолчанию, а также параметры учетной записи Azure Cosmos DB по умолчанию для создания этих коллекций. Поэтому мы не можем определить параметры создания, такие как пропускная способность, ключ сегментирования или параметры автомасштабирования с помощью этих методов.

Используя API Azure Cosmos DB для MongoDB, вы можете воспользоваться преимуществами Cosmos DB. Эти преимущества включают глобальное распределение, автоматическое сегментирование, высокий уровень доступности, гарантии задержки, автоматическое шифрование неактивных данных, резервное копирование и многое другое. Кроме того, добавлено преимущество сохранения инвестиций в приложение MongoDB. С API-интерфейсом Azure Cosmos DB для MongoDB можно взаимодействовать, используя любой из драйверов клиента MongoDB с открытым кодом. API Azure Cosmos DB для MongoDB позволяет использовать имеющиеся драйверы клиента благодаря сетевому протоколу MongoDB.

Давайте создадим код, позволяющий создать коллекцию и определить его ключ сегментирования и пропускную способность.

  1. Откройте Cloud Shell Azure, если вы этого еще не сделали.

  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. Следующий шаг подключается к базе данных employees. Если эта база данных не существует, она создает ее только в том случае, если также создается коллекция в том же соединении или с помощью команд расширения. Добавьте следующий код в скрипт в редакторе.

      // 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), чтобы вернуться к Shell.

  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.

Завершив это упражнение, мы перейдем к вопросам проверки знаний в рамках этого модуля.