LoginSignup
1
1

More than 3 years have passed since last update.

MongoDB学習日記 - 2019/12/12

Last updated at Posted at 2019-12-12

目的

  1. MongoDBに接続する
  2. CRUD実現

MongoDBに接続する

1、 GradleでDriverをImportする

build.gradle
dependencies {
    // Mongo db
    compile 'org.mongodb:mongo-java-driver:3.12.0'
}

2、MongoDBに接続して、データ抽出してみる

        // MongoDBサーバに接続
        MongoClient mongoClient = MongoClients.create("mongodb://<user>:<password>@ds253428.mlab.com:53428/heroku_c3swt6jb");
        MongoDatabase database = mongoClient.getDatabase("heroku_c3swt6jb");
        MongoCollection<Document> collection = database.getCollection("parking_lot");
        Document myDoc = collection.find().first();
        System.out.println(myDoc.toJson());
        System.out.println(myDoc.get("id"));

        // サーバから切断
        mongoClient.close();

3、CRUD実現

        // MongoDBサーバに接続
        MongoClient mongoClient = MongoClients.create(
                "mongodb://<user>:<password>@ds253428.mlab.com:53428/heroku_c3swt6jb?retryWrites=false");
        MongoDatabase database = mongoClient.getDatabase("heroku_c3swt6jb");
        MongoCollection<Document> collection = database.getCollection("parking_lot");

        // create
        Document doc = new Document("id", "testid").append("name", "C1-11.haha").append("ParkingEntID","a").append("ParkingLat","b").append("ParkingLon","c");
        collection.insertOne(doc);

        // read
        Document myDoc = collection.find(eq("id","testid")).first();
        System.out.println("this is old one: " + myDoc.toJson());

        // update
        Document docNew = new Document("id", "testid").append("name", "C1-11.haha.New").append("ParkingEntID","a").append("ParkingLat","b").append("ParkingLon","c");;
        collection.updateOne(eq("id","testid"), new Document("$set", docNew));

        // read to check if data updated correctly
        myDoc = collection.find(eq("id","testid")).first();
        System.out.println("this is new one: " + myDoc.toJson());

        // delete
        collection.deleteMany(eq("id","testid"));

        // サーバから切断
        mongoClient.close();

ハマったところ

1、接続時エラー
driver version: 3.12.0
mongoDB version: 3.6.9
mongoDBのバージョンが古くて、retryWritesという新しい機能をサポートしないためです。
対策は、mongoDBのURIに、query parameterのretryWrites=falseを追加。

com.mongodb.MongoClientException: This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.

2、Update時エラー

java.lang.IllegalArgumentException: Invalid BSON field name id

原因はこんなCommandだった:

collection.updateOne(eq("id","testid"), docNew);

正しいのは

collection.updateOne(eq("id","testid"), new Document("$set", docNew));

References

Description URL
HP of MongoDB driver URL
1
1
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
1