Java + MongoDB Hello World Example--转载
原文地址: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 :
- MongoDB 2.2.3
- MongoDB-Java-Driver 2.10.1
- JDK 1.6
- Maven 3.0.3
- 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.
<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);
}
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.
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--转载的更多相关文章
- 【MongoDB数据库】Java MongoDB CRUD Example
上一页告诉我们MongoDB 命令入门初探,本篇blog将基于上一篇blog所建立的数据库和表完毕一个简单的Java MongoDB CRUD Example.利用Java连接MongoDB数据库,并 ...
- 想了解JAVA的,看看(转载)
较新一篇 / 较旧一篇 编辑 |删除 | 复制链接 公开 想了解JAVA的,看看(转载)2009-03-01 15:41 (分类:默认分类) 先总结一下: J2SE (Core/Desktop) ...
- Java NIO Channel之FileChannel [ 转载 ]
Java NIO Channel之FileChannel [ 转载 ] @author zachary.guo 对于文件 I/O,最强大之处在于异步 I/O(asynchronous I/O),它允许 ...
- Java 序列化 序列化与单例模式 [ 转载 ]
Java 序列化 序列化与单例模式 [ 转载 ] @author Hollis 本文将通过实例+阅读Java源码的方式介绍序列化是如何破坏单例模式的,以及如何避免序列化对单例的破坏. 单例模式,是设计 ...
- 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 ...
- java MongoDB查询(二)复杂查询
前言 在上篇<java MongoDB查询(一)简单查询>中我们简单了解了下查询,但是仅仅有那些查询是不够用的,还需要复杂的查询,这篇就这点进行叙述. 1.数据结构 集合:firstCol ...
- Java mongodb api疑问之MongoCollection与DBCollection
在学习Java mongodb api时发现,可以调用不同的java mongodb api来连接数据库并进行相关操作. 方式一: 该方式使用mongoClient.getDB("xxx&q ...
- java.util.ConcurrentModificationException 解决办法(转载)
今天在项目的中有一个需求,需要在一个Set类型的集合中删除满足条件的对象,这时想当然地想到直接调用Set的remove(Object o)方法将指定的对象删除即可,测试代码: public cla ...
- JAVA线程安全总结(转载)
JAVA线程安全总结(一) JAVA线程安全总结(二) 最近想将java基础的一些东西都整理整理,写下来,这是对知识的总结,也是一种乐趣.已经拟好了提纲,大概分为这几个主题: java线程安全,jav ...
随机推荐
- 巧用CSS文件愚人节恶搞(转)
明天就是4月1日愚人节了,也就是那个可适度开玩笑.整蛊的日子了.如果你想和那些要上网的朋友或同事开个极客式玩笑,那就来试试这个国外网友Wes Bos分享的 CSS 文件吧. 一.打开浏览器的 Cust ...
- ListView属性
1. 背景色: listView设置背景色android:background="@drawable/bg",拖动或者点击list空白位置的时候发现ListItem都变成黑色. 因 ...
- LeetCode题解——Median of Two Sorted Arrays
题目: 找两个排序数组A[m]和B[n]的中位数,时间复杂度为O(log(m+n)). 解法: 更泛化的,可以找第k个数,然后返回k=(m+n)/2时的值. 代码: class Solution { ...
- ExtJS 5.0版本问题+Sencha cmd
ExtJS 5.0版本官方网站给的图表例子,以散点图作说明: Ext.create('Ext.Container', { //renderTo: Ext.getBody(), width: 600, ...
- uva 2218 Triathlon
题意:铁人三项赛,给定每个选手游泳,自行车,赛跑三个阶段的平均速度,不知道每段比赛的路程,询问当前这个选手能否胜利. 思路:把题意转化为一个不等式,设比赛长度是1,如果i要战胜j,x.y分别是第一阶段 ...
- HW7.1
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner i ...
- hdu5773--The All-purpose Zero(LIS变形)
题意:给一个非负整数的数列,其中0可以变成任意整数,包括负数,求最长上升子序列的长度. 题解:LIS是最简单的DP了,但是变形之后T^T真的没想到.数据范围是10^5,只能O(nlogn)的做法,所以 ...
- ABAP报表程序编写规范 .
一. 程序的结构: 典型的ABAP报表程序是由多个代码区域组成,各代码区的存放位置以下列顺序为准,具体格式如下: *----------------------------- ...
- 关于CSS样式优先级
一般情况下: [1位重要标志位] > [4位特殊性标志] > 声明先后顺序 !important > [ id > class > tag ] 使用!important可 ...
- 【Stage3D学习笔记续】山寨Starling(七):一般优化方法简介及混合模式
关于事件的优化: 遍历注册的事件由foreach改变为fori,在大量数据遍历时会有提升: 事件池优化: 所有的事件都使用一个对象池进行保存,而不是使用到时进行创建,使用EventDispatcher ...