原文地址: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. ViewPager onPageChangeListener总结

    今天在做项目的时候,由于要处理viewPager页面滑动的事件,所以对其进行了一个小小的研究: 首先ViewPager在处理滑动事件的时候要用到OnPageChangeListener OnPageC ...

  2. 《深入Java虚拟机学习笔记》- 第13章 逻辑运算

    <深入Java虚拟机学习笔记>- 第13章 浮点运算

  3. TPL

    namespace TPLTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } pr ...

  4. mac usb转串口 连接树莓PI

    USB 转串口是淘宝买的 http://item.taobao.com/item.htm?spm=a1z09.2.9.50.YOJBwG&id=38963495468&_u=4m1dr ...

  5. 中断——中断描述符表的定义和初始化(一) (基于3.16-rc4)

    1.中断描述符表的定义(arch/x86/kernel/traps.c) gate_desc debug_idt_table[NR_VECTORS] __page_aligned_bss; 定义的描述 ...

  6. 【Hadoop学习】Apache Hadoop项目简介

    正在撰写,稍后来访……

  7. 单点登录与消息队列以及在J2EE中的实现方案

    前言 这次为大家简单介绍两个在WEB开发中经常使用的概念——单点登录和消息队列以及具体到J2EE中的一些实现方案.本文原创性的工作比较少,主要是一些总结概括和自己的理解. 单点登录SSO SSO的业务 ...

  8. Visual Studio中的Build Event

    在VS中,进行build时,可以在build之前,或者之后执行一些操作,比如把一些css,font,images文件从一个项目的文件夹复制到另一个项目的文件夹 方法: 点击项目,右键-属性-Build ...

  9. 转载 SharePoint 2013 Search功能

    转载原出处: http://www.cnblogs.com/OceanEyes/p/SharePont-2013-Search-Develop.html 阅读目录 启用Search Service A ...

  10. UVA 10779 Collectors Problem(最大流)

    这个题是很难往网络流上面构思的... 从s向每个物品增加容量为Bob拥有数的弧,然后从每个物品向t增加容量为1的弧(代表种类个数).这时候跑最大流的话,得到的肯定是Bob拥有的初始种类数.那么交换后的 ...