Java MongoDB hello worldの例

単純なJava MongoDBのhello worldの例 – データベース(データベース)の作成、コレクションと文書の作成、保存、更新、削除、取得、表示の方法の例です。
使用されるツールと技術:
-
MongoDB 2.2.3
-
MongoDB-Java-Driver 2.10.1
-
JDK 1.6
-
Maven 3.0.3
-
Eclipse 4.2
__P.S MavenとEclipseはどちらもオプションですが、個人的に好きな開発ツールです。
1. Javaプロジェクトを作成する
Mavenを使ってリンク://maven/how-to-create-a-java-project-with-maven/[単純なJavaプロジェクト]を作成します。
mvn archetype:generate -DgroupId=com.mkyong.core -DartifactId=mongodb -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
2. Mongo Java Driverを入手する
github
からmongo-javaドライバをダウンロードしてください。 Mavenユーザの場合、 `pom.xml`にmongo-javaドライバを宣言します。
pom.xml
<project ...>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. Mongo接続
MongoDBサーバーに接続します。 MongoDBバージョン> = 2.10.0では、 `MongoClient`を使用します。
//Old version, uses Mongo
Mongo mongo = new Mongo("localhost", 27017);
//Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient( "localhost" , 27017 );
MongoDBがセキュアモードの場合、認証が必要です。
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("database name");
boolean auth = db.authenticate("username", "password".toCharArray());
4. Mongoデータベース
データベースを取得します。データベースが存在しない場合は、MongoDBによって作成されます。
DB db = mongo.getDB("database name");
すべてのデータベースを表示します。
List<String> dbs = mongo.getDatabaseNames();
for(String db : dbs){
System.out.println(db);
}
5.モンゴーコレクション
コレクション/テーブルを取得します。
DB db = mongo.getDB("testdb");
DBCollection table = db.getCollection("user");
選択したデータベースのすべてのコレクションを表示します。
DB db = mongo.getDB("testdb");
Set<String> tables = db.getCollectionNames();
for(String coll : tables){
System.out.println(coll);
}
6.サンプルの保存
ドキュメント(データ)を “user”という名前のコレクション(テーブル)に保存します。
DBCollection table = db.getCollection("user");
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
document.put("createdDate", new Date());
table.insert(document);
このリンク://mongodb/java-mongodb-insert-a-document/[Java MongoDBの挿入例]を参照してください。
7.更新例
“name = mkyong”のドキュメントを更新します。
DBCollection table = db.getCollection("user");
BasicDBObject query = new BasicDBObject();
query.put("name", "mkyong");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "mkyong-updated");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
このリンク://mongodb/java-mongodb-update-document/[Java MongoDBの更新例]を参照してください。
8.例を見つける
“name = mkyong”の文書を検索し、DBCursorで表示します
DBCollection table = db.getCollection("user");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
このリンク://mongodb/java-mongodb-query-document/[Java MongoDB検索クエリの例]を参照してください。
9.削除例
“name = mkyong”の文書を見つけて削除してください。
DBCollection table = db.getCollection("user");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
table.remove(searchQuery);
このリンク://mongodb/java-mongodb-delete-document/[Java MongoDB delete example]を参照してください。
10. Hello World
完全なJava MongoDBの例を見てみましょう。コメントは自明です。
App.java
package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
/** **
** Java + MongoDB Hello world Example
**
** /public class App {
public static void main(String[]args) {
try {
/** ** ** ** Connect to MongoDB ** ** ** ** / //Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient("localhost", 27017);
/** ** ** ** Get database ** ** ** ** / //if database doesn't exists, MongoDB will create it for you
DB db = mongo.getDB("testdb");
/** ** ** ** Get collection/table from 'testdb' ** ** ** ** / //if collection doesn't exists, MongoDB will create it for you
DBCollection table = db.getCollection("user");
/** ** ** ** Insert ** ** ** ** / //create a document to store key and value
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
document.put("createdDate", new Date());
table.insert(document);
/** ** ** ** Find and display ** ** ** ** / BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
/** ** ** ** Update ** ** ** ** / //search document where name="mkyong" and update it with new values
BasicDBObject query = new BasicDBObject();
query.put("name", "mkyong");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "mkyong-updated");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
/** ** ** ** Find and display ** ** ** ** / BasicDBObject searchQuery2
= new BasicDBObject().append("name", "mkyong-updated");
DBCursor cursor2 = table.find(searchQuery2);
while (cursor2.hasNext()) {
System.out.println(cursor2.next());
}
/** ** ** ** Done ** ** ** ** / System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
出力…
{ "__id" : { "$oid" : "51398e6e30044a944cc23e2e"} , "name" : "mkyong" , "age" : 30 , "createdDate" : { "$date" : "2013-03-08T07:08:30.168Z"}}
{ "__id" : { "$oid" : "51398e6e30044a944cc23e2e"} , "age" : 30 , "createdDate" : { "$date" : "2013-03-08T07:08:30.168Z"} , "name" : "mkyong-updated"}
Done
`mongo`コンソールを使用して、作成されたデータベース” testdb “、コレクション” user “、およびドキュメントを確認しましょう。
$ mongo
MongoDB shell version: 2.2.3
connecting to: test
> show dbs
testdb 0.203125GB
> use testdb
switched to db testdb
> show collections
system.indexes
user
> db.user.find()
{ "__id" : ObjectId("51398e6e30044a944cc23e2e"), "age" : 30, "createdDate" : ISODate("2013-03-08T07:08:30.168Z"), "name" : "mkyong-updated" }
ソースコードをダウンロードする
ダウンロードする –
Java-mongodb-hello-world-example.zip
(13KB)