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 并发工具包 java.util.concurrent 用户指南
- 菜鸟的mongoDB学习---(六)MongoDB 索引
- Java数据类型—BigDecimal
- Java mongoDB实现layIM版web即时通讯系统
- Java IO: 异常处理
- JAVA础--利用java反射机制绕过编译时的类型检查和访问控制检查
- JAVA基础--Java枚举+位操作,巧妙判断是否设置
- CSDN日报191016:Java纯干货分享:史上最全的JAVA工程师面试题汇总
- 玩转MongoDB—使用Go和Java客户端
- Java - CentOS下JDK的安装教程(及JAVA_HOME配置、以jdk1.8为例)
- Java面向对象继承
- java中判断list是否为空的用法
- java.net.SocketException: 权限不够
- 基于Java(SSH框架)+MySQL实现(Web)学生成绩管理系统【100010355】
- 基于Java+Mysql实现在线书店订购系统【100010003】
- Java NIO三组件——Selecotr/Channel实现原理解析
- Java日期时间使用总结
- Java开发环境配置(Win7 64位系统/server 2008)
- java.lang.OutOfMemoryError: Java heap space解决方法
- java日期处理类总结:Date/Calendar/GregorianCalendar/DateFormat/SimpleDateFormat类
- Java_基础知识回顾
- java 保留字符串数字的位数,不够前面补0
- 『Java练习生的自我修养』java-se进阶³ • 线程的等待与唤醒
- 华为OD机试 -数字加减游戏(Java) | 机试题+算法思路+考点+代码解析 【2023】
- Java集合框架1
- Java高手速成│实战:应用数据库和GUI开发产品销售管理软件(2)
- 浅谈如何用Java操作MongoDB?
- Oracle:推迟了的Java Enterprise Edition 8将会在“今年之内”发布
- java 面向对象编程——简介
- 【mongodb】Jemeter调用Python操作mongoDB压测
- Java线程同步
- Java EE 7 / JAX-RS 2.0: Simple REST API Authentication & Authorization with Custom HTTP Header--reference
- Exception from System.loadLibrary(smjavaagentapi) java.lang.UnsatisfiedLinkError: no smjavaagentapi in java.library.path
- maven管理的jsp应用如何添加servlet、jsp相关依赖(org.apache.jasper.JasperException: java.lang.ClassNotFoundException: org.apache.jsp.index_jsp)
- 【JAVA】浅谈java枚举类
- Java 报错 Information:java: javacTask: 源发行版 8 需要目标发行版 1.8
- 解决Java使用response下载文件报错,并总结可能出错的原因: java.io.IOException: 你的主机中的软件中止了一个已建立的连接。