LoginSignup
1
0

Autonomous JSON Database(AJSON) で MongoDB Java CRUD Tutorial を実行してみる(Oracle Cloud Infrastructure)

Last updated at Posted at 2024-03-26

表題の通り OCI の Autonomous JSON Database(AJSON) で MongoDB の下記チュートリアルを実行してみるやで。
彡(^)(^)

Getting Started with MongoDB and Java - CRUD Operations Tutorial
https://www.mongodb.com/developer/languages/java/java-setup-crud-operations/

1. 環境

下記記事の環境を流用します。mongodb.uriに記載する接続情報も下記記事を参照して下さい。

2. SAMPLE_TRAININGスキーマ(ユーザー)の作成と権限付与

Oracle Database API for MongoDB(≒AJSON)の場合、MongoDB のデータベースに相当するものが Oracle Database ではスキーマになります。

1 Oracle Database API for MongoDBの概要
1.3 用語および概念: MongoDBおよびOracle Database
https://docs.oracle.com/cd/F58797_01/mgapi/overview-oracle-database-api-mongodb.html#GUID-D6DC46B0-EA98-47E9-8EAD-5CB6E04DC64E
データベース …コレクションのセット。Oracle Databaseでは、これはデータベースのスキーマに対応します。データベースという用語の使用は混乱を招く可能性があるため、このドキュメントではOracle Databaseに対してはデータベースという用語を使用し、MongoDBでデータベースと呼んでいるものに対してはスキーマまたはデータベース・スキーマという用語を使用しています。

該当チュートリアルのサンプル・プログラムでは sample_training という MongoDB のデータベースに接続しているため、対応する SAMPLE_TRAININGスキーマ(ユーザー)を AJSON に作成して権限を付与します。

CREATE USER SAMPLE_TRAINING IDENTIFIED BY xxxxxxxx
DEFAULT TABLESPACE USERS
TEMPORARY TABLESPACE TEMP;
GRANT SODA_APP, CREATE SESSION, CREATE TABLE, CREATE VIEW, CREATE SEQUENCE, CREATE PROCEDURE, CREATE JOB, UNLIMITED TABLESPACE, DWROLE TO SAMPLE_TRAINING;
EXECUTE ORDS.ENABLE_SCHEMA(p_schema => 'SAMPLE_TRAINING');

3. Oracle JDK 21 のインストール

該当チュートリアルは Java 21以降が必要なので JDK 21 をインストールします。JDK はいまや百花繚乱ですが今回は Oracle JDK 21 を選択します。

JDK Development Kit 21.0.2 downloads
https://www.oracle.com/jp/java/technologies/downloads/#java21

今回は rpmパッケージ をダウンロードして localinstall します。

wget https://download.oracle.com/java/21/latest/jdk-21_linux-x64_bin.rpm
sudo dnf localinstall ./jdk-21_linux-x64_bin.rpm

インストール後にバージョンを確認します。

[opc@ays-prvcomp1 mongo]$ java -version
java version "21.0.2" 2024-01-16 LTS
Java(TM) SE Runtime Environment (build 21.0.2+13-LTS-58)
Java HotSpot(TM) 64-Bit Server VM (build 21.0.2+13-LTS-58, mixed mode, sharing)

4. Maven のダウンロードと展開

該当チュートリアルでは Maven 3.8.7以上が推奨されていたため、Apache のサイトからダウンロードして展開します。

Downloading Apache Maven 3.9.6
https://maven.apache.org/download.cgi

今回は Maven 3.9.6 の .tar.gz版をダウンロードして /home/opc/mongo/配下に展開しました。

cd /home/opc/mongo
wget https://dlcdn.apache.org/maven/maven-3/3.9.6/binaries/apache-maven-3.9.6-bin.tar.gz
tar xvzf ./apache-maven-3.9.6-bin.tar.gz

5. git のインストールとリポジトリclone

git をインストールしてチュートリアルのリポジトリを clone します。/home/opc/mongo配下 に clone します。
なおチュートリアルのファイル群は zip でもダウンロード可能なので git は必須ではありません。

sudo dnf install git
cd /home/opc/mongo
git clone https://github.com/mongodb-developer/java-quick-start

6. MongoDB Java Tutorial の Connection を実行

MongoDB Java Tutorial の Connection を実行します。Maven でビルドして実行します。JAVA_HOME指定 および Maven にパスを通してビルド&実行します。AJSON の接続情報はMavenコマンドの-Dオプションでmongodb.uriというプロパティに定義します。パスワードの記号類は前回記事同様に%でクォートします。

cd /home/opc/mongo/java-quick-start
export JAVA_HOME=/usr/lib/jvm/jdk-21-oracle-x64/
export PATH=/home/opc/mongo/apache-maven-3.9.6/bin:${JAVA_HOME}/bin:${PATH}
mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Connection" -Dmongodb.uri='mongodb://SAMPLE_TRAINING:xxxxxxxx@xxxxx.adb.ap-osaka-1.oraclecloudapps.com:27017/sample_training?authMechanism=PLAIN&authSource=$external&ssl=true&retryWrites=false&loadBalanced=true'
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.mongodb:java-quick-start >--------------------
[INFO] Building java-quick-start 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ java-quick-start ---
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO]
[INFO] --- compiler:3.12.1:compile (default-compile) @ java-quick-start ---
[INFO] Recompiling the module because of changed source code.
[INFO] Compiling 18 source files with javac [debug target 21] to target/classes
[INFO]
[INFO] --- exec:3.1.1:java (default-cli) @ java-quick-start ---
=> Print result of the '{ping: 1}' command.
{
  "ok": 1.0
}
=> Connection successful: true
=> Print list of databases:
{"name": "sample_training", "empty": true, "sizeOnDisk": 0.0}
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.912 s
[INFO] Finished at: 2024-03-26T08:33:50Z
[INFO] ------------------------------------------------------------------------
[opc@ays-prvcomp1 java-quick-start]$

チュートリアルの Connection が上手く動作しました。

7. MongoDB Java Tutorial の Create を実行

MongoDB Java Tutorial の Create を実行します。Maven でビルドして実行します。JAVA_HOME指定, Mavenパス, AJSON接続情報は同様です。

cd /home/opc/mongo/java-quick-start
export JAVA_HOME=/usr/lib/jvm/jdk-21-oracle-x64/
export PATH=/home/opc/mongo/apache-maven-3.9.6/bin:${JAVA_HOME}/bin:${PATH}
mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Create" -Dmongodb.uri='mongodb://SAMPLE_TRAINING:xxxxxxxx@xxxxx.adb.ap-osaka-1.oraclecloudapps.com:27017/sample_training?authMechanism=PLAIN&authSource=$external&ssl=true&retryWrites=false&loadBalanced=true'
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.mongodb:java-quick-start >--------------------
[INFO] Building java-quick-start 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ java-quick-start ---
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO]
[INFO] --- compiler:3.12.1:compile (default-compile) @ java-quick-start ---
[INFO] Nothing to compile - all classes are up to date.
[INFO]
[INFO] --- exec:3.1.1:java (default-cli) @ java-quick-start ---
One grade inserted for studentId 10000.
Ten grades inserted for studentId 10001.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.176 s
[INFO] Finished at: 2024-03-26T08:36:22Z
[INFO] ------------------------------------------------------------------------
[opc@ays-prvcomp1 java-quick-start]$

上手く動作したようです。mongosh で AJSON に接続して、作成されたコレクション(GRADES)の中身を確認してみます。

mongosh 'mongodb://SAMPLE_TRAINING:xxxxxxxx@xxxxx.adb.ap-osaka-1.oraclecloudapps.com:27017/sample_training?authMechanism=PLAIN&authSource=$external&ssl=true&retryWrites=false&loadBalanced=true'

Current Mongosh Log ID: 66028980910efee193c00e7d
Connecting to:          mongodb://<credentials>@xxxxx.adb.ap-osaka-1.oraclecloudapps.com:27017/sample_training?authMechanism=PLAIN&authSource=%24external&ssl=true&retryWrites=false&loadBalanced=true&appName=mongosh+2.2.1
Using MongoDB:          4.2.14
Using Mongosh:          2.2.1

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

sample_training> show collections
grades
sample_training> db.grades.find()
[
  {
    _id: ObjectId('66028905db6a46269341d672'),
    student_id: 10000,
    class_id: 1,
    scores: [
      { type: 'exam', score: 39.171184726656385 },
      { type: 'quiz', score: 18.838605035253075 },
      { type: 'homework', score: 90.57462029798369 },
      { type: 'homework', score: 86.28030232545281 }
    ]
  },

  {
    _id: ObjectId('66028906db6a46269341d67c'),
    student_id: 10001,
    class_id: 10,
    scores: [
      { type: 'exam', score: 6.3328784853445175 },
      { type: 'quiz', score: 60.481518579211304 },
      { type: 'homework', score: 21.243834848554087 },
      { type: 'homework', score: 36.46916491537853 }
    ]
  }
]
sample_training>

データもセットされていました。

8. MongoDB Java Tutorial の Read を実行

MongoDB Java Tutorial の Read を実行します。Maven でビルドして実行します。JAVA_HOME指定, Mavenパス, AJSON接続情報は同様です。

mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Read" -Dmongodb.uri='mongodb://SAMPLE_TRAINING:xxxxxxxx@xxxxx.adb.ap-osaka-1.oraclecloudapps.com:27017/sample_training?authMechanism=PLAIN&authSource=$external&ssl=true&retryWrites=false&loadBalanced=true'
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.mongodb:java-quick-start >--------------------
[INFO] Building java-quick-start 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ java-quick-start ---
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO]
[INFO] --- compiler:3.12.1:compile (default-compile) @ java-quick-start ---
[INFO] Nothing to compile - all classes are up to date.
[INFO]
[INFO] --- exec:3.1.1:java (default-cli) @ java-quick-start ---
Student 1: {"_id": {"$oid": "66028905db6a46269341d672"}, "student_id": 10000.0, "class_id": 1.0, "scores": [{"type": "exam", "score": 39.171184726656385}, {"type": "quiz", "score": 18.838605035253075}, {"type": "homework", "score": 90.57462029798369}, {"type": "homework", "score": 86.28030232545281}]}
Student 2: {"_id": {"$oid": "66028905db6a46269341d672"}, "student_id": 10000.0, "class_id": 1.0, "scores": [{"type": "exam", "score": 39.171184726656385}, {"type": "quiz", "score": 18.838605035253075}, {"type": "homework", "score": 90.57462029798369}, {"type": "homework", "score": 86.28030232545281}]}
Student list with a cursor:
{"_id": {"$oid": "66028905db6a46269341d672"}, "student_id": 10000.0, "class_id": 1.0, "scores": [{"type": "exam", "score": 39.171184726656385}, {"type": "quiz", "score": 18.838605035253075}, {"type": "homework", "score": 90.57462029798369}, {"type": "homework", "score": 86.28030232545281}]}

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.590 s
[INFO] Finished at: 2024-03-26T08:46:04Z
[INFO] ------------------------------------------------------------------------

こちらも上手く動作しました。

9. MongoDB Java Tutorial の Update を実行

MongoDB Java Tutorial の Update を実行します。Maven でビルドして実行します。JAVA_HOME指定, Mavenパス, AJSON接続情報は同様です。

mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Update" -Dmongodb.uri='mongodb://SAMPLE_TRAINING:xxxxxxxx@xxxxx.adb.ap-osaka-1.oraclecloudapps.com:27017/sample_training?authMechanism=PLAIN&authSource=$external&ssl=true&retryWrites=false&loadBalanced=true'
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.mongodb:java-quick-start >--------------------
[INFO] Building java-quick-start 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ java-quick-start ---
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO]
[INFO] --- compiler:3.12.1:compile (default-compile) @ java-quick-start ---
[INFO] Nothing to compile - all classes are up to date.
[INFO]
[INFO] --- exec:3.1.1:java (default-cli) @ java-quick-start ---
=> Updating the doc with {"student_id":10000}. Adding comment.
{
  "_id": {
    "$oid": "66028905db6a46269341d672"
  },
  "student_id": 10000.0,
  "class_id": 1.0,
  "scores": [
    {
      "type": "exam",
      "score": 39.171184726656385
    },
    {
      "type": "quiz",
      "score": 18.838605035253075
    },
    {
      "type": "homework",
      "score": 90.57462029798369
    },
    {
      "type": "homework",
      "score": 86.28030232545281
    }
  ],
  "comment": "You should learn MongoDB!"
}
AcknowledgedUpdateResult{matchedCount=1, modifiedCount=1, upsertedId=null}

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.034 s
[INFO] Finished at: 2024-03-26T08:53:14Z
[INFO] ------------------------------------------------------------------------

動作しました。mongosh で AJSON に接続して、更新されたコレクション(GRADES)の中身を確認してみます。

mongosh 'mongodb://SAMPLE_TRAINING:xxxxxxxx@xxxxx.adb.ap-osaka-1.oraclecloudapps.com:27017/sample_training?authMechanism=PLAIN&authSource=$external&ssl=true&retryWrites=false&loadBalanced=true'
Current Mongosh Log ID: 66028deb571091ce4cc00e7d
Connecting to:          mongodb://<credentials>@xxxxx.adb.ap-osaka-1.oraclecloudapps.com:27017/sample_training?authMechanism=PLAIN&authSource=%24external&ssl=true&retryWrites=false&loadBalanced=true&appName=mongosh+2.2.1
Using MongoDB:          4.2.14
Using Mongosh:          2.2.1

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

sample_training> db.grades.find({"student_id": 10000})
[
  {
    _id: ObjectId('66028905db6a46269341d672'),
    student_id: 10000,
    scores: [
      { type: 'exam', score: 78.34236945331277 },
      { type: 'quiz', score: 18.838605035253075 },
      { type: 'homework', score: 90.57462029798369 },
      { type: 'homework', score: 86.28030232545281 }
    ],
    comment: 'You should learn MongoDB!',
    x: 10,
    new_class_id: 1,
    comments: [ 'This comment is uniq' ]
  }
]
sample_training>

コメントが挿入されていることが確認できました。

10. まとめ

Autonomous JSON Database で MongoDB Java CRUD Tutorial を動作させることができました。
Autonomous JSON Database は大変お安いので、皆さんどんどん活用して下さいね。
彡(^)(^)

Autonomous Databaseの価格
https://www.oracle.com/jp/autonomous-database/pricing/

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0