[A-00218] MongoDB事始め(Java)
javaでmongodbを使う方法を記載しておく。
基本的にDockerで動かしますので下記のコマンドを実行してmongodbサーバーを起動します。
#!/bin/bash
docker run -itd \
 -e MONGO_INITDB_ROOT_USERNAME=root \
 -e MONGO_INITDB_ROOT_PASSWORD=pass \
 -e MONGO_INITDB_DATABASE=documents \
 -p 27017:27017 \
 --name mongo \
 mongo上記のshellを実行して下記のコマンドでコンテナ内に入ります。
docker exec -it mongo bashDockerコンテナ内部でmongoshを実行してmongodbに接続します。
mongosh -u root -p pass上記でログインしたら[test]というdbに接続します。下記のコマンドを実行して適当なデータを作成する。
test> db.users.insert({username:"tanaka"})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
  acknowledged: true,
  insertedIds: { '0': ObjectId('670165903c24baa23c964033') }
}
test> db.users.insert({username:"sasaki"})
{
  acknowledged: true,
  insertedIds: { '0': ObjectId('670165a63c24baa23c964034') }
}
findで追加したデータを確認します。
test> db.users.find()
[
  { _id: ObjectId('670165903c24baa23c964033'), username: 'tanaka' },
  { _id: ObjectId('670165a63c24baa23c964034'), username: 'sasaki' }
]上記でmongodb側の準備ができたのでjavaで接続してみます。
mavenに下記のdependencyを追加します。driverです。
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongodb-driver-sync</artifactId>
			<version>5.2.0</version>
		</dependency>javaのプログラムは下記です。
package com.example.common;
import static java.util.Collections.singletonList;
import org.bson.Document;
import com.mongodb.Block;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.connection.ClusterSettings;
public class MongoConnection {
    public static void main(String[] args) throws Exception {
        MongoCredential credential = MongoCredential.createCredential("root", "admin", "pass".toCharArray());
        Block<ClusterSettings.Builder> localhost = builder -> builder.hosts(singletonList(new ServerAddress("localhost", 27017)));
        MongoClientSettings settings = MongoClientSettings.builder()
        .applyToClusterSettings(localhost)
        .credential(credential)
        .build();
        try( MongoClient client = MongoClients.create(settings)) {
        MongoCollection<Document> col = client.getDatabase("test").getCollection("users");
        System.out.println(col.countDocuments());
        FindIterable<Document> iterable = col.find();
        iterable.forEach((doc) -> System.out.println(doc));
        }
    }
}上記を実行すると下記のような結果になります。
2
Document{{_id=670165903c24baa23c964033, username=tanaka}}
Document{{_id=670165a63c24baa23c964034, username=sasaki}}以上で基本的な動作確認ができました。
・データをインサートする
mongodbにデータを登録します。
package com.example.common;
import static java.util.Collections.singletonList;
import org.bson.Document;
import com.mongodb.Block;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.connection.ClusterSettings;
public class MongoInsert {
    public static void main(String[] args) throws Exception {
                MongoCredential credential = MongoCredential.createCredential("root", "admin", "pass".toCharArray());
        Block<ClusterSettings.Builder> localhost = builder -> builder.hosts(singletonList(new ServerAddress("localhost", 27017)));
        MongoClientSettings settings = MongoClientSettings.builder()
        .applyToClusterSettings(localhost)
        .credential(credential)
        .build();
        try( MongoClient client = MongoClients.create(settings)) {
        MongoCollection<Document> col = client.getDatabase("test").getCollection("users");
        Document user = new Document();
        user.append("username", "suzuki");
        col.insertOne(user);
        }
    }
}test> db.users.find()
[
  { _id: ObjectId('670165903c24baa23c964033'), username: 'tanaka' },
  { _id: ObjectId('670165a63c24baa23c964034'), username: 'sasaki' },
  { _id: ObjectId('67016d293789ec43f3b2cd45'), username: 'suzuki' }
]プログラム実行後にfindで確認すると3レコードになっていたので正常に動作しました。
・複数レコードのインサート
複数レコードをインサートする場合は下記になります。
package com.example.common;
import java.util.ArrayList;
import static java.util.Collections.singletonList;
import java.util.List;
import org.bson.Document;
import com.mongodb.Block;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.connection.ClusterSettings;
public class MongoInsertMany {
    public static void main(String[] args) throws Exception {
                MongoCredential credential = MongoCredential.createCredential("root", "admin", "pass".toCharArray());
        Block<ClusterSettings.Builder> localhost = builder -> builder.hosts(singletonList(new ServerAddress("localhost", 27017)));
        MongoClientSettings settings = MongoClientSettings.builder()
        .applyToClusterSettings(localhost)
        .credential(credential)
        .build();
        try( MongoClient client = MongoClients.create(settings)) {
        MongoCollection<Document> col = client.getDatabase("test").getCollection("users");
        List<Document> userList = new ArrayList<>();
        Document user1 = new Document();
        user1.append("username", "hashimoto");
        Document user2 = new Document();
        user2.append("username", "hayashi");
        userList.add(user1);
        userList.add(user2);
        col.insertMany(userList);
        }
    }
}実行後、レコードは下記になります。
test> db.users.find()
[
  { _id: ObjectId('670165903c24baa23c964033'), username: 'tanaka' },
  { _id: ObjectId('670165a63c24baa23c964034'), username: 'sasaki' },
  { _id: ObjectId('67016d293789ec43f3b2cd45'), username: 'suzuki' },
  { _id: ObjectId('67016f689f56e83bb63ba243'), username: 'hashimoto' },
  { _id: ObjectId('67016f689f56e83bb63ba244'), username: 'hayashi' }
]複数レコード増えているので正常に動いたようです。
・Appendix
参考文献はこちら
https://zenn.dev/hashito/articles/f036b50c3c33d1
https://qiita.com/chenglin/items/3c4cea19c24ac6993434
https://www.mongodb.com/ja-jp/docs/drivers/go/current/fundamentals/auth
コメントを残す