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

使用java操作MongoDB Demo
public class Demo {

	public static void main(String[] args) {
		Mongo conn = null;
		DB db = null;
		try {
			conn = new Mongo("localhost", 27017);
			db = conn.getDB( "test" );
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}

		
		/**获取所有collection**/
		for (String s : db.getCollectionNames()) {
		    System.out.println(s);
		}

		/**获取一个collection**/
		DBCollection coll = db.getCollection("testCollection");

        BasicDBObject doc = new BasicDBObject();
        doc.put("name", "MongoDB");
        doc.put("type", "database");
        doc.put("count", 1);

        BasicDBObject info = new BasicDBObject();

        info.put("x", 203);
        info.put("y", 102);

        doc.put("info", info);

        /**插入Document**/
        coll.insert(doc);
		
		/**调试**/
        
        DBObject myDoc = coll.findOne();
        System.out.println(myDoc);
        
        /******************************************/
        
        /**插入多个document**/
        for (int i=0; i < 100; i++) {
            coll.insert(new BasicDBObject().append("i", i));
        }

        /**计算有多少个document**/
        System.out.println(coll.getCount());


        /**使用DBCursor 类获取所有document**/
        DBCursor cur = coll.find();

        while(cur.hasNext()) {
             System.out.println(cur.next());
        }
        
        
        /**带条件的查询**/
        BasicDBObject query = new BasicDBObject();

        query.put("i", 98);  //查i的值为98的所有对象

        cur = coll.find(query);

        while(cur.hasNext()) {
            System.out.println(cur.next());
        }

        
        /**解析json格式的字符串**/
		Object o = JSON.parse("{ \"name\" : \"MongoDB\", \"type\" : \"database\",\"count\" : 1, \"info\" : \"sdfsdf\"}");
		
		BasicDBObject oo = (BasicDBObject)o;
		
		System.out.println(oo.get("name"));
        
	}
	
}