Java操作MongoDB快速入门教程

MongoDB基础 01/03 阅读 4981 views次 人气 643
摘要:

Java操作MongoDB代码,实现了最基础的CRUD操作,每个操作都有单独的方法可以运行。

Mongodb驱动下载: 地址: http://docs.mongodb.org/manual/applications/drivers/ 下载链接:http://pan.baidu.com/s/1i35nczV 密码:y2xk   Mongodb在线JavaAPI: http://api.mongodb.org/java/current/   Mongodb创建数据库、用户名和密码: use demo; db.demo.insert({name:'demo'}); db.addUser('root','root123')   Java操作MongoDB代码实例:
package com.what21.mongodb.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;

public class OperateDemo {

	/**
	 * @return
	 * @throws Exception
	 */
	public static MongoClient getMongoClient()throws Exception{
		try {
			//===================================================//
			List<ServerAddress> serverList = new ArrayList<ServerAddress>();
			serverList.add(new ServerAddress("192.168.18.85", 27017));
			//===================================================//
			List<MongoCredential> mcList = new ArrayList<MongoCredential>();
			String username = "root";
			String database = "demo";
			char[] password = "root123".toCharArray();
			mcList.add(MongoCredential.createCredential(username, database,password));
			//===================================================//
			MongoClientOptions.Builder builder = MongoClientOptions.builder();
			// 与目标数据库能够建立的最大connection数量为50 
			builder.connectionsPerHost(50);  
			// 如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待  
			builder.threadsAllowedToBlockForConnectionMultiplier(50); 
			// 一个线程访问数据库的时候,在成功获取到一个可用数据库连接之前的最长等待时间为2分钟 
			// 这里比较危险,如果超过maxWaitTime都没有获取到这个连接的话,该线程就会抛出Exception 
			// 故这里设置的maxWaitTime应该足够大,以免由于排队线程过多造成的数据库访问失败 
			builder.maxWaitTime(1000*60*2);  
			// 与数据库建立连接的timeout设置为1分钟  
			builder.connectTimeout(1000*60*1);   
			//===================================================//
			MongoClientOptions mco = builder.build(); 
			return new MongoClient(serverList, mcList, mco);
		} catch (Exception e) {
			throw e;
		}
	}
	
	/**
	 * @param dbname
	 * @return
	 * @throws Exception
	 */
	public static DB getDB(String dbname) throws Exception{
		return getMongoClient().getDB(dbname);
	}
	
	/**
	 * @param db
	 */
	public static void collections(DB db){
		Set<String> colls = db.getCollectionNames();
		for (String collName : colls) {
		    System.out.println(collName);
		}
	}
	
	/**
	 * @param db
	 * @param name
	 */
	public static void insert(DB db,String name){
		DBCollection dbColl = db.getCollection(name);
		WriteResult result = null;
		List<DBObject> objectList = new ArrayList<DBObject>();
		for(int i=0;i<100;i++){
			BasicDBObject obj = new BasicDBObject();  
			obj.put("name", "name" + (i+1));
			obj.put("email", "email@" + (i+1) + ".com");
			obj.put("passwd", "p" + (i+1));
			objectList.add(obj);
		}
		result = dbColl.insert(objectList);
		System.out.println(result);
	}
	
	/**
	 * @param db
	 * @param name
	 */
	public static void findOne(DB db,String name){
		DBCollection dbColl = db.getCollection("users");
		for(int i=0;i<100;i++){
			BasicDBObject query = new BasicDBObject();  
			query.put("name", "name" + (i+1));
			DBObject obj = dbColl.findOne(query);
			System.out.print("name=" + obj.get("name"));
	    	System.out.print(",email=" + obj.get("email"));
	    	System.out.println(",passwd=" + obj.get("passwd"));
		}
	}
	
	/**
	 * @param db
	 * @param name
	 */
	public static void update(DB db,String name){
		DBCollection dbColl = db.getCollection(name);
		WriteResult result = null;
		for(int i=0;i<100;i++){
			BasicDBObject query = new BasicDBObject();  
			query.put("name", "name" + (i+1));
			DBObject obj = dbColl.findOne(query);
			obj.put("email", "email" + (i+1) + "@qq.com");
			result = dbColl.update(query, obj);
			System.out.println(result);
		}
	}
	
	/**
	 * @param db
	 * @param name
	 */
	public static void remove(DB db,String name){
		DBCollection dbColl = db.getCollection(name);
		WriteResult result = null;
		for(int i=0;i<100;i++){
			BasicDBObject obj = new BasicDBObject();  
			obj.put("name", "name" + (i+1));
			result = dbColl.remove(obj);
			System.out.println(result);
		}
	}
	
	/**
	 * @param db
	 * @param name
	 */
	public static void queryAll(DB db,String name){
		DBCollection dbColl = db.getCollection(name);
		DBCursor cur = dbColl.find();
		int count = 0;
	    while (cur.hasNext()) {
	    	DBObject obj = cur.next();
	    	System.out.print("name=" + obj.get("name"));
	    	System.out.print(",email=" + obj.get("email"));
	    	System.out.println(",passwd=" + obj.get("passwd"));
	    	count ++;
	    }
	    System.out.println("共有: " + count + "个");
	}
	
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		DB db = getDB("demo");
		collections(db);
		String name = "users";
		System.out.println("insert()=================================================");
		insert(db,name);
		System.out.println("findOne()=================================================");
		findOne(db,name);
		System.out.println("update()=================================================");
		update(db,name);
		System.out.println("findOne()=================================================");
		findOne(db,name);
		System.out.println("remove()=================================================");
		remove(db,name);
		System.out.println("queryAll()=================================================");
		queryAll(db,name);
	}

}

评论

该文章不支持评论!

分享到: