博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java + MongoDB Hello World Example--转载
阅读量:7296 次
发布时间:2019-06-30

本文共 6763 字,大约阅读时间需要 22 分钟。

原文地址: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  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 . For Maven users, declares mongo-java driver in pom.xml.

pom.xml
 
org.mongodb
mongo-java-driver
2.10.1
 
 
org.apache.maven.plugins
maven-compiler-plugin
2.3.1
1.6
1.6
org.apache.maven.plugins
maven-eclipse-plugin
true
true
 
 

. 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
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
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 .

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 .

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 .

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 .

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.

$ mongoMongoDB shell version: 2.2.3connecting to: test > show dbstestdb	0.203125GB > use testdbswitched to db testdb > show collectionssystem.indexesuser> db.user.find(){ "_id" : ObjectId("51398e6e30044a944cc23e2e"), "age" : 30, "createdDate" : ISODate("2013-03-08T07:08:30.168Z"), "name" : "mkyong-updated" }

 

转载地址:http://ohynm.baihongyu.com/

你可能感兴趣的文章
java springcloud版b2b2c社交电商spring cloud分布式微服务 (四) 断路器(Hystrix)
查看>>
java B2B2C Springboot电子商务平台源码-Feign设计原理
查看>>
canvas使用技巧大全
查看>>
BCH压力测试悄然开始?有优势但也有不足!
查看>>
swift SDWebImage 与 UIButton 出现的细节bug 不显示
查看>>
彻底搞懂JavaScript执行机制
查看>>
Java版本多用户B2B2C商城源码-(八)消息总线(Spring Cloud Bus)
查看>>
spring cloud java b2b2c o2o分布式 微服务电子商务平台
查看>>
kafka集群安装
查看>>
理解ThreadLocal 2
查看>>
基于Shibbloet实现的SSO单点登录
查看>>
SimpleDraw-Windows Phone7上的应用
查看>>
在js中使用createElement创建HTML对象和元素_无需整理
查看>>
ubuntu14.6 密码重置_已迁移
查看>>
笔记 1
查看>>
Python中:self和__init__的含义 + 为何要有self和__init__
查看>>
第十二章 网络管理-centos7.5知识
查看>>
java的枚举类enum
查看>>
Hive 和普通关系数据库的异同
查看>>
影评~~
查看>>