原文地址:http://www.mkyong.com/mongodb/java-mongodb-hello-world-example/

A simple Java + MongoDB hello world example – how to connect, create database, collection and document, save, update, remove, get and display document (data).

Tools and technologies used :

  1. MongoDB 2.2.3
  2. MongoDB-Java-Driver 2.10.1
  3. JDK 1.6
  4. Maven 3.0.3
  5. Eclipse 4.2

P.S Maven and Eclipse are both optional, just my personal favorite development tool.

1. Create a Java Project

Create a simple Java project with Maven.

mvn archetype:generate -DgroupId=com.mkyong.core -DartifactId=mongodb
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

2. Get Mongo Java Driver

Download mongo-java driver from github. For Maven users, declares mongo-java driver in pom.xml.

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>

. Mongo Connection

Connect to MongoDB server. For MongoDB version >= 2.10.0, uses MongoClient.

	// Old version, uses Mongo
Mongo mongo = new Mongo("localhost", 27017);
 
// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient( "localhost" , 27017 );

If MongoDB in secure mode, authentication is required.

	MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("database name");
boolean auth = db.authenticate("username", "password".toCharArray());

4. Mongo Database

Get database. If the database doesn’t exist, MongoDB will create it for you.

	DB db = mongo.getDB("database name");

Display all databases.

	List<String> dbs = mongo.getDatabaseNames();
for(String db : dbs){
System.out.println(db);
}

5. Mongo Collection

Get collection / table.

	DB db = mongo.getDB("testdb");
DBCollection table = db.getCollection("user");

Display all collections from selected database.

	DB db = mongo.getDB("testdb");
Set<String> tables = db.getCollectionNames();
 
for(String coll : tables){
System.out.println(coll);
}
Note
In RDBMS, collection is equal to table.

6. Save example

Save a document (data) into a collection (table) named “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);

Refer to this Java MongoDB insert example.

7. Update example

Update a document where “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);

Refer to this Java MongoDB update example.

8. Find example

Find document where “name=mkyong”, and display it with 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());
}

Refer to this Java MongoDB search query example.

9. Delete example

Find document where “name=mkyong”, and delete it.

	DBCollection table = db.getCollection("user");
 
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
 
table.remove(searchQuery);

Refer to this Java MongoDB delete example.

10. Hello World

Let review a complete Java + MongoDB example, see comments for self-explanatory.

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();
}
 
}
}

Output…

{ "_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

Let use mongo console to check the created database “testdb”, collection “user”, and document.

$ 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--转载的更多相关文章

  1. 【MongoDB数据库】Java MongoDB CRUD Example

    上一页告诉我们MongoDB 命令入门初探,本篇blog将基于上一篇blog所建立的数据库和表完毕一个简单的Java MongoDB CRUD Example.利用Java连接MongoDB数据库,并 ...

  2. 想了解JAVA的,看看(转载)

    较新一篇 / 较旧一篇 编辑 |删除 | 复制链接  公开 想了解JAVA的,看看(转载)2009-03-01 15:41 (分类:默认分类) 先总结一下: J2SE   (Core/Desktop) ...

  3. Java NIO Channel之FileChannel [ 转载 ]

    Java NIO Channel之FileChannel [ 转载 ] @author zachary.guo 对于文件 I/O,最强大之处在于异步 I/O(asynchronous I/O),它允许 ...

  4. Java 序列化 序列化与单例模式 [ 转载 ]

    Java 序列化 序列化与单例模式 [ 转载 ] @author Hollis 本文将通过实例+阅读Java源码的方式介绍序列化是如何破坏单例模式的,以及如何避免序列化对单例的破坏. 单例模式,是设计 ...

  5. Java MongoDB : Save image example

    In this tutorial, we show you how to save an image file into MongoDB, via GridFS API. The GridFS API ...

  6. java MongoDB查询(二)复杂查询

    前言 在上篇<java MongoDB查询(一)简单查询>中我们简单了解了下查询,但是仅仅有那些查询是不够用的,还需要复杂的查询,这篇就这点进行叙述. 1.数据结构 集合:firstCol ...

  7. Java mongodb api疑问之MongoCollection与DBCollection

    在学习Java mongodb api时发现,可以调用不同的java mongodb api来连接数据库并进行相关操作. 方式一: 该方式使用mongoClient.getDB("xxx&q ...

  8. java.util.ConcurrentModificationException 解决办法(转载)

    今天在项目的中有一个需求,需要在一个Set类型的集合中删除满足条件的对象,这时想当然地想到直接调用Set的remove(Object o)方法将指定的对象删除即可,测试代码:   public cla ...

  9. JAVA线程安全总结(转载)

    JAVA线程安全总结(一) JAVA线程安全总结(二) 最近想将java基础的一些东西都整理整理,写下来,这是对知识的总结,也是一种乐趣.已经拟好了提纲,大概分为这几个主题: java线程安全,jav ...

随机推荐

  1. disabled

    http://blog.csdn.net/dinglang_2009/article/details/6974887 如果把页面viewstate设为disabled 那么 ispost就一直为fal ...

  2. android Bitmap getByteCount和getRowBytes

    今天做图像缓存需要计算Bitmap的所占的内存空间,于是研究了下Bitmap关于内存占用的API 1.getRowBytes:Since API Level 1,用于计算位图每一行所占用的内存字节数. ...

  3. uboot环境变量与内核MTD分区关系

    uboot 与系统内核中MTD分区的关系: 分区只是内核的概念,就是说A-B地址放内核,C-D地址放文件系统,(也就是规定哪个地址区间放内核或者文件系统)等等. 1:在内核MTD中可以定义分区A~B, ...

  4. POJ 3377 Ferry Lanes

    虽然它出现在dp专场里···但是我第一反应是一道最短路题···不过幸好它出现在dp专场里···因为我不怎么会dijstra什么的··· 题意:一条河上有N+1对码头,每个相邻码头之间需要一定时间到达, ...

  5. (Android Studio)添加按钮以及权重问题

    此文大部分摘自http://hukai.me/android-training-course-in-chinese/basics/firstapp/building-ui.html 注意到光标所在代码 ...

  6. [Bhatia.Matrix Analysis.Solutions to Exercises and Problems]ExI.5.6

    Let $A$ be a nilpotent operator. Show how to obtain, from aJordan basis for $A$, aJordan basis of $\ ...

  7. java中的final关键字

    谈到final关键字,想必很多人都不陌生,在使用匿名内部类的时候可能会经常用到final关键字.另外,Java中的String类就是一个final类,那么今天我们就来了解final这个关键字的用法.下 ...

  8. 同样的JS写法,为啥只有IE9模式正常?

    使用 IE F12 开发者工具,选择不同的“文档模式” 从IE7 - IE9,只有IE9正常! <!DOCTYPE html> <html> <script type=& ...

  9. FL2440移植Linux2.6.33.7内核

    kernel version:2.6.33.7 /linux-2.6.33.7 OS:CentOS 6.4 cross-compilation chain:arm-linux-4.3.2 /usr/l ...

  10. JDBCTemplate.java

    package com.pk.xjgs.util; import java.sql.Connection; import java.sql.SQLException; import java.util ...