Java Azure Cosmos DB (MongoDB) の Document 削除 on Ubuntu No.47

自己投資の一つとしてチャレンジしている Programming の Java の独習状況を Blog で公開しています。今回は Azure Cosmos DB API for MongoDB の Document の Delete について紹介します。

————————————
▼1. Azure Cosmos DB API for MongoDB を操作する Java の library
————————————
Azure Cosmos DB API for MongoDB のデータを操作する Java の library といっても、Azure を扱う Microsoft 社が提供する Library は存在せず、OpenSource の MongoDB を操作する library org.mongodb の MongoDB Java Driver を使って、Azure の Cosmos DB MongoDB のデータを操作できます。その他、MongoDB を操作できるライブラリーは複数あり C, C++, C#, Go, Node.js, PHP, Python, Ruby, Rust, Scala, Swift が挙げられます。(参考) https://docs.mongodb.com/drivers/

————————————
▼2. 事前準備
————————————
Ubuntuの環境で Java を動かしています。

2-1. 以下のサイトから無料で利用できる Azure Cosmos DB を用意します。Azure を利用するために必要な Subscription を用意する必要もありません。
https://azure.microsoft.com/ja-jp/try/cosmosdb/

2-2.  IntelliJ IDEA のインストール
詳細はこちらの blog を参照ください。

https://www.kumoman.net/site/2021/11/11/java-intellij-no43-2021-11/

2-3. Maven auto-import を IntelliJ IDEA で有効にします(ubuntu で IntelliJ IDEA をインストールしています)。
詳細はこちらの blog を参照ください。

https://www.kumoman.net/site/2020/07/12/intellij-enabling-auto-import-no13-2020-07/

2-4. Pom.xml に以下のように必要なライブラリーを指定します。その後、上記 2-3 設定により、ライブラリーが自動でダウンロードされます。
(参考) https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver/3.12.10

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.10</version>
        </dependency>
    </dependencies>

2-5. 削除対象のデータの追加方法は前回の Blog で紹介しています。

https://www.kumoman.net/site/2022/02/01/java-azure-cosmosdb-mongodb-ubuntu-no-46-2022-02/

————————————
▼3. Azure Cosmos DB API for MongoDB の Document の削除
————————————
3-1. 以下のコードで Azure Cosmos DB に接続し、Document (データ) を削除します。DeleteDocuments の関数の中で Document を削除しています。1 行の document を削除するには deleteOne を利用し、複数の documents を削除するには deleteMany の関数を利用します。

connectionString には接続文字列を入れ、dbName  および collName にそれぞれ利用する DB 名と Collection 名を入れます。

(例)
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoException;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import org.bson.Document;

public class ConnCosmosDBMongoDBv3 {
    String connectionString ="mongodb://xxxx.documents.azure.com:10255/?ssl=true";
    String dbName = "dbname";
    String collName = "collectionname";
    MongoClient client;

    public void InitMongoClient()
    {
        MongoClientOptions.Builder optionBuilder = new MongoClientOptions.Builder();
        // Set values to prevent timeouts
        optionBuilder.socketTimeout(10000);
        optionBuilder.maxConnectionIdleTime(60000);
        optionBuilder.heartbeatConnectTimeout(5000);

        MongoClientURI mongoClientURI = new MongoClientURI(this.connectionString, optionBuilder);
        this.client = new MongoClient(mongoClientURI);
    }

    public void ReadWriteDocuments() {
        System.out.println("Reading documents.");
        try {
            MongoCollection<Document> coll = this.client.getDatabase(this.dbName).getCollection(this.collName);

            // Add the document
            Document document = new Document("LName","Greek");
            document.append("Sku","G4");
            document.append("Name","Middle");
            document.append("Price","800");
            coll.insertOne(document);

            // Read the document
            Document queryResult = coll.find(Filters.eq("LName","Greek")).first();
            if (queryResult != null) {
                System.out.println("===");
                System.out.println(queryResult.toJson());
            }
        } catch (MongoException me) {
            System.out.println("Exception:" + me);
        }
    }

    public void DeleteDocuments() {
        System.out.println("Reading documents.");
        try {
            MongoCollection<Document> coll = this.client.getDatabase(this.dbName).getCollection(this.collName);
            // Delete one document
            //coll.deleteOne(Filters.eq("LName","Greek"));
            // Delete multiple documents
            coll.deleteMany(Filters.eq("LName","Greek"));
            System.out.println("The deletion was complete.");
        } catch (MongoException me) {
            System.out.println("Exception:" + me);
        }
    }

    public void RunCode() {
        System.out.println("Start the application ConnCosmosDBMongoDBv3.");
        InitMongoClient();
        ReadWriteDocuments();
        DeleteDocuments();
        System.out.println("Completed the application ConnCosmosDBMongoDBv3.");
    }

    public static void main(String[] args) {
        ConnCosmosDBMongoDBv3 appMongo = new ConnCosmosDBMongoDBv3();
        appMongo.RunCode();
    }
}

3-2. 実行結果は以下となります。
追加した LName が Greek の document を参照後、削除しています。

(例)
Start the application ConnCosmosDBMongoDBv3.
Feb 07, 2022 11:47:56 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[xxxx.documents.azure.com:10255], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Reading documents.
Feb 07, 2022 11:47:56 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster description not yet available. Waiting for 30000 ms before timing out
Feb 07, 2022 11:47:57 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:7xxx}] to xxxx.documents.azure.com:10255
Feb 07, 2022 11:47:57 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=xxxx.documents.azure.com:10255, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=2, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=null, roundTripTimeNanos=107733717, setName='globaldb', canonicalAddress=xxxx.documents.azure.com:10255, hosts=[xxxx.documents.azure.com:10255], passives=[], arbiters=[], primary='xxxx.documents.azure.com:10255', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=null, lastUpdateTimeNanos=3272362741837}
Feb 07, 2022 11:47:58 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:1953768959}] to xxxx.documents.azure.com:10255
===
{"_id": {"$oid": "16xxxx4"}, "LName": "Greek", "Sku": "G4", "Name": "Middle", "Price": "800"}
Reading documents.
The deletion was complete.
Completed the application ConnCosmosDBMongoDBv3.

————————————
▼4. 参考情報
————————————
(1) Azure Cosmos DB を無料で試す https://docs.microsoft.com/ja-jp/azure/cosmos-db/optimize-dev-test#try-azure-cosmos-db-for-free
(2) https://docs.mongodb.com/drivers/
(3) https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
(4) https://www.kumoman.net/site/2022/02/01/java-azure-cosmosdb-mongodb-ubuntu-no-46-2022-02/
(5) https://docs.mongodb.com/manual/reference/method/db.collection.deleteOne/
(6) https://docs.mongodb.com/manual/reference/method/db.collection.deleteMany/

以上です。参考になりましたら幸いです。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です