MongoDB Java Driver メモ

# MongoDB Java Driver で Java から MongoDB を利用する

* CentOS7
* MongoDB 3.2
* Java 1.8.0_77
* Maven 3.3.9
* MongoDB Java Driver 3.4.1

## MongoDBのインストール
### リポジトリの追加

```
# vi /etc/yum.repos.d/mongodb-org-3.2.repo
```

```
[mongodb-org-3.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/
gpgcheck=0
enabled=1
```

### yumでインストール

```
# yum install mongodb-org
```

### サービスの起動

```
# service mongod start
```

### 自動起動の設定

```
# systemctl enable mongod
```

### MongoDB shell でテストデータを追加しておく

```
# mongo
> use test_db
> db.test_coll.insert({"title":"test001","data":"hogehoge"})
```

## Mavenのインストール
※jdkを事前にインストールしJAVA_HOMEを設定しておく。
### 公式サイトからapache-maven-3.3.9-bin.tar.gzをダウンロード。
[Maven Download](http://maven.apache.org/download.cgi#)
### /opt/で解凍

```
# cp  apache-maven-3.3.9-bin.tar.gz /opt/
# cd /opt/
# tar xzvf apache-maven-3.3.9-bin.tar.gz
```

### 環境変数設定

```
# vi /etc/profile.d/maven.sh
```

```
export M3_HOME=/opt/apache-maven-3.3.9
M3=$M3_HOME/bin
export PATH=$M3:$PATH
```

```
# source /etc/profile
```

```
# mvn -v
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-11T01:41:47+09:00)
Maven home: /opt/apache-maven-3.3.9
Java version: 1.8.0_77, vendor: Oracle Corporation
Java home: /usr/java/jdk1.8.0_77/jre
Default locale: ja_JP, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-514.2.2.el7.x86_64", arch: "amd64", family: "unix"
```

## Mavenのプロジェクト作成
### Mavenのコマンドでプロジェクト作成

```
# mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
```

```
# tree
.
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── mycompany
    │               └── app
    │                   └── App.java
    └── test
        └── java
            └── com
                └── mycompany
                    └── app
                        └── AppTest.java

```
### pom.xmlの設定
Maven Assembly Pluginで実行可能jarを作る

```
  <plugins>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <version>3.0.0</version>
      <configuration>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <archive>
          <manifest>
            <mainClass>com.mycompany.app.App</mainClass>
          </manifest>
        </archive>
      </configuration>
      <executions>
        <execution>
          <id>make-assembly</id> <!-- this is used for inheritance merges -->
          <phase>package</phase> <!-- bind to the packaging phase -->
          <goals>
            <goal>single</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
```

MongoDB Java Driverの依存関係の設定

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

warning対策

```
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
```

### App.javaでMongoDBにアクセス

```
package com.mycompany.app;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.BasicDBObject;
import org.bson.Document;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        String host = "localhost";
        int port = 27017;
        String databaseName = "test_db";
        String collectionName = "test_coll";

        MongoClient mongoClient = new MongoClient(host, port);
        MongoDatabase database = mongoClient.getDatabase(databaseName);
        MongoCollection<Document> coll = database.getCollection(collectionName);

        BasicDBObject query = new BasicDBObject();
        query.put("title", "test001");
        System.out.println(query);

        FindIterable<Document> find = coll.find(query);
        MongoCursor<Document> cursor = find.iterator();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }

        long count = coll.count(query);
        System.out.println(count + "件");
        mongoClient.close();
    }
}
```

### ビルド

```
mvn clean package
```

### 実行

```
java -cp target/my-app-1.0-SNAPSHOT-jar-with-dependencies.jar com.mycompany.app.App
```