[CENTOS] MongoDB Java Driver Note

Use MongoDB from Java with MongoDB Java Driver

Install MongoDB

Add repository

# 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

Install with yum

# yum install mongodb-org

Service startup

# service mongod start

Auto start settings

# systemctl enable mongod

Add test data with MongoDB shell

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

Maven installation

Download apache-maven-3.3.9-bin.tar.gz from the official website.

Maven Download

Unzip with / opt /

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

Environment variable settings

# 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 project creation

Create project with Maven command

# 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 settings

Make an executable jar with Maven Assembly Plugin

  <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 Dependency Settings

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

warning measures

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

Access MongoDB with App.java

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 + "Case");
        mongoClient.close();
    }
}

Build

mvn clean package

Run

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

Recommended Posts

MongoDB Java Driver Note
[Note] Operate MongoDB with Python
Note
Note
How to build MongoDB C driver