原文出自:http://www.mkyong.com/mongodb/java-mongodb-hello-world-example/
返回目录:http://ysj5125094.iteye.com/blog/2192754
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).
译:一个简单的利用Java + MongoDB实现hello world例子 —— 如何连接,创建数据库、集合和文档,保存、更新、删除、获取和显示文档(数据)。
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.
译:P.S Maven和Eclipse是可选的,只是我个人最喜欢的开发工具。
1. Create a Java Project
Create a simple Java project with Maven.
译:创建一个简单的Maven Java project项目。
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
.
译:从github下载mongo-java驱动。mgongo-java驱动声明在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>
3. Mongo Connection
Connect to MongoDB server. For MongoDB version >= 2.10.0, uses MongoClient
.
译:使用MongoClient连接MongoDB server。MongoDB版本 >= 2.10.0
// 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.
译:获取数据库。如果数据库不存在,那么MongoDB会自动创建。
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”.
译:在"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.
译:请参数这个Java MongoDB插入的例子。
7. Update example
Update a document where “name=mkyong”.
译:更新条件为“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
译:查询条件为"name=mkyong"的文档,并显示所有数据游标内容。
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.
译:查询条件为"name=mkyong"的文档并删除他。
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.
译:让我们一起来审查已完成的Java + MongoDB例子,
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控制台来检查创建的数据库"testdb",集合"user"和文档。
$ 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" }
Download Source Code
附件可以下载源代码
References
相关推荐
图书管理系统,java+express+mongodb+nodejs+gulp.zip 图书管理系统,java+express+mongodb+nodejs+gulp.zip 图书管理系统,java+express+mongodb+nodejs+gulp.zip 图书管理系统,java+express+mongodb+nodejs+...
主要介绍了java+MongoDB实现存图片、下载图片的方法,结合实例形式详细分析了java结合MongoDB实现图片的存储与下载相关操作技巧,需要的朋友可以参考下
django+mongodb+hui 实现的后台管理系统.zipdjango+mongodb+hui 实现的后台管理系统.zipdjango+mongodb+hui 实现的后台管理系统.zipdjango+mongodb+hui 实现的后台管理系统.zipdjango+mongodb+hui 实现的后台管理...
SpringBoot+MongoDB+Echarts图表数据可视化 SpringBoot+MongoDB+Echarts图表数据可视化
资源中存有springmongo配置,mongo数据库相关配置,mongo实现类等等
前端 Vue+Node+MongoDB高级全栈开发
SpringBoot+Redis+Mqtt+MongoDB全部配置完成,下载Redis+Mqtt+MongoDB三个程序,把项目导入idea中再把SQL导入数据库下好依赖即可,注意Redis,MongoDB,Mqtt账户信息,如不一致可更换成自己的,CURD已完成
Node.js+Express+MongoDB实现简单登录注册功能,压缩包中包含了所需模块,直接可以用
PHP高级工程师必知必会Nginx+keepalived+MongoDB+haproxy+Sphinx实现分布式集群部署实战视频
java基于jsoup+mongodb的简单爬虫入门程序,简单易懂,希望能给大家提供帮助
Python + MongoDB开发的百度云爬虫.zipPython + MongoDB开发的百度云爬虫.zipPython + MongoDB开发的百度云爬虫.zipPython + MongoDB开发的百度云爬虫.zipPython + MongoDB开发的百度云爬虫.zipPython + MongoDB开发...
基于springboot+mongodb搭建的简约个人博客系统 基于springboot+mongodb搭建的简约个人博客系统 基于springboot+mongodb搭建的简约个人博客系统 基于springboot+mongodb搭建的简约个人博客系统 基于springboot+...
基于SpringBoot + Mybatis + Thymeleaf +Redis+MongoDB+MySQL开发的商品管理系统。基于SpringBoot + Mybatis + Thymeleaf +Redis+MongoDB+MySQL开发的商品管理系统。基于SpringBoot + Mybatis + Thymeleaf +Redis+...
nodejs+express+mongodb 博客系统增删改查完整版,包括用户注册,博客发表,博客修改,博客删除,权限控制。后台连接mongodb:blog
NULL 博文链接:https://flycun2.iteye.com/blog/1906539
基于NodeJS+Express+mongoDB+Bootstrap的全栈式工程化开发前后端分离博客系统实战
物流管理系统源码,基于spirngboot+mongodb+layui.zip
这是一个简单的express+mongodb+node的例子,如果1要运行的话需要安装node环境还有mongodb数据库,里面是一个简单的博客平台的例子,很适合初学者,而且代码我都有大量的注释,很好看懂
试文档