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 ...
随机推荐
- service name和SID的区别
数据库名(DB_NAME).实例名(Instance_name).以及操作系统环境变量(ORACLE_SID) 在ORACLE7.8数据库中只有数据库名(db_name)和数据库实例名(instan ...
- SQL Server 2008 R2主数据服务安装
SQL Server 2008 R2的主数据服务(Master Data Services,简称MDS)已经放出,目前是CTP版本,微软提供了下载地址: http://www.microsoft.co ...
- HDU 4389 X mod f(x)
题意:求[A,B]内有多少个数,满足x % f(x) == 0. 解法:数位DP.转化为ans = solve(b) - solve(a - 1).设dp[i][sum][mod][r]表示长度为i, ...
- swift学习之一致性hash
转自:http://blog.csdn.net/cywosp/article/details/23397179 一致性哈希算法在1997年由麻省理工学院提出的一种分布式哈希(DHT)实现算法,设计目标 ...
- 【暑假】[实用数据结构]UVa11235 Frequent values
UVa 11235 Frequent values Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 11241 Accep ...
- 1351 topcoder 吃点心
https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1351 先按low从大到小贪心再high从小到大贪心 #pragma c ...
- 2016"百度之星" - 复赛(Astar Round3) 1003 拍照
拍照 思路:先静态,离线树状数组,分别统计每个点向左向右能看到的船的数量.再枚举整个区间求最大值. 应为人和船都是动态的,假设船往左走,处理每个点看到向左最大船的数量,满足动态条件.就是向左的船一开始 ...
- uvalive 4513 Stammering Aliens
题意:给你一个串,问期中至少出现m次的最长子串及其起始位置的坐标. 思路:hash+LCP+二分答案 #include<cstdio> #include<cstring> #i ...
- sprintf的缓冲区溢出
sprintf的缓冲区溢出 分类: 技术2010-03-07 15:26 362人阅读 评论(0) 收藏 举报 今天,调试sector的时候遇到一个特奇怪的问题,程序会在取string的c_str() ...
- 关于main()和_tmain()
1.两者的共同点 int _tmain(int argc, _TCHAR* argv[]) 和 int main(int argc, char* argv[]) ,两者都是程序的主函数,两者 ...