日期:2014-05-16  浏览次数:20540 次

mongodb java 增删改查
package com.mgtest;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

public class Leantest {
	
	Mongo mongoClient = null;
	DB db = null;
	DBCollection coll = null;
	
	public Leantest(){
		try {
			mongoClient = new Mongo("localhost", 27017);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		db = mongoClient.getDB("test");
		coll = db.getCollection("testCollection");
	}
	
	public void insert(){
		BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type",
				"database").append("count", 1).append("info",
				new BasicDBObject("x", 203).append("y", 102));
		coll.insert(doc);
		
		BasicDBObject doc1 = new BasicDBObject("name", "struts").append("type",
		"mvc").append("count1", 1).append("info1",
		new BasicDBObject("x1", 203).append("y1", 102));
		coll.insert(doc1);
		
		BasicDBObject doc2 = new BasicDBObject("name", "spring").append("type",
		"service").append("count2", 1).append("info2",
		new BasicDBObject("x2", 111).append("y2", 22));
		coll.insert(doc2);
		
		
		queryAll();
	}
	
	public void queryAll(){
		DBCursor cursor = coll.find();
		try {
		   while(cursor.hasNext()) {
		       System.out.println(cursor.next());
		   }
		} finally {
		   cursor.close();
		}
		System.out.println("总数为:"+coll.count());
	}
	
	public void delete(){
		DBObject doc = new BasicDBObject("name", "MongoDB");
		coll.remove(doc);

		
		queryAll();
	}
	
	public void update(){
		BasicDBObject q = new BasicDBObject("name", "struts");
		BasicDBObject o = new BasicDBObject("name", "struts_new");
		coll.update(q, o);

		
		queryAll();
	}
	
	public void find(){
		BasicDBObject o = new BasicDBObject("name", "struts_new");
		DBCursor cursor = coll.find(o);
		try {
		   while(cursor.hasNext()) {
		       System.out.println(cursor.next());
		   }
		} finally {
		   cursor.close();
		}
	}

	public static void main(String[] args) throws UnknownHostException {
		Leantest lt = new Leantest();
		//lt.insert();
		//lt.delete();
		//lt.update();
		lt.find();
	}

}

?

附件下载mongodb的jar包