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

MongoDB程序开发之使用Java驱动

在工作中使用到了MongoDB,平时也看了一些资料,感觉MongoDB官网内develop zone有个不错的manual,很多资料都可以查到,地址如下:http://www.mongodb.org/display/DOCS/Manual

?

另外,本blog主要记录一下使用mongodb java driver来访问数据库的一些总结。

?

?主要是由createMongoInstance()方法完成初始化工作。

protected static final Mongo mongoInstance = createMongoInstance();

private static Mongo createMongoInstance() {
        MongoOptions mo = new MongoOptions();
        mo.socketKeepAlive=true;
        mo.autoConnectRetry = true;
        mo.maxAutoConnectRetryTime=10;
        mo.connectionsPerHost = 40;
        mo.connectTimeout = 20 * 1000;
        mo.socketTimeout = 60 * 1000;
        try {
            if (DatabaseProject.DB_CONFIG.containsKey("mongodb.ips")) {
                return new Mongo(getServerAddrsFromConf("mongodb"),mo);
            }
            return new Mongo(new ServerAddress(DatabaseProject.DB_CONFIG.getString("mongodb.ip"), DatabaseProject.DB_CONFIG.getInt("mongodb.port")),mo);

        } catch (Throwable e) {
            DatabaseProject.LOGGER.error("Failed to init mongodb", e);
            throw new ExceptionInInitializerError(e);
        }
    }

? 其中有一些数据库配置直接写在配置文件里了,在MongoJavaDriverDAO中初始化一部分数据:

?

public void insertCollData(){
		//如果该collection不存在则会自动创建
		DBCollection parentcoll = getCollection("ParentColl");
		DBCollection childcoll = getCollection("ChildColl");
		for(int i=0;i<1000;i++){
			DBObject document = new BasicDBObject();
			document.put("intData", 1000+i);
			document.put("longData", System.currentTimeMillis());
			document.put("strData", UUID.randomUUID().toString());
			document.put("doubleData", 1.123+i);
			document.put("createDate", new Date());
			document.put("booleanData", true);
			DBObject innerDoc = new BasicDBObject();
			innerDoc.put("innertype", "string");
			innerDoc.put("innerContent", "string"+i);
			document.put("documentData", innerDoc);
			parentcoll.insert(document);
			DBObject childDocument = new BasicDBObject();
			childDocument.put("parentId", document.get("_id"));
			childDocument.put("createDate", new Date());
			List list = new ArrayList();
			list.add("str" + i%10);
			list.add("str" + i%20);
			list.add(new BasicDBObject("arr"+(i%10),(i%10)));
			list.add(new BasicDBObject("arr"+(i%20),(i%20)));
			childDocument.put("arrays",list);
			childcoll.insert(childDocument);
		}
		System.out.println("ParentColl Count:"+parentcoll.count());
		System.out.println("ChildColl Count:"+childcoll.count());
	}

?其中getCollection方法会获取集合,不存在的话会自动创建一个。getCollection方法如下:

?

public static DBCollection getCollection(String collectionName){
	return getDB().getCollection(collectionName);
}

?现在创建了2个集合ParentColl、ChildColl,并初始化了数据。

查询相关方法:

?

/**
	 * 查询全部数据
	 */
	public void findColl(){
		coll = getCollection("ParentColl");
		DBCursor cur = coll.find();
		while(cur.hasNext()){
	        System.out.println(cur.next());
	    }
		System.out.println("Count:"+coll.count());
	}
	
	/**
	 * 根据ObjectId查询
	 */
	public void findById(String id){
		coll = getCollection("ParentColl");
		DBCursor cur = coll.find(new BasicDBObject("_id", new ObjectId(id)));//直接用string查不出来
		while(cur.hasNext()){
	        System.out.println(cur.next());
	    }
	}
	
	/**
	 * And多条件查询
	 */
	public void findByAndQuery(int intData,long longData){
		coll = getCollection("ParentColl");
		BasicDBObject query = new BasicDBObject();
		query.put("intData", intData);
		query.put("longData", longData);
		System.out.println(coll.findOne(query));
	}
	
	/**
	 * OR多条件查询
	 */
	public void findByORQuery(int lte,int gt,long longData){
		coll = getCollection("ParentColl");
		BasicDBObject query=new BasicDBObject();
		BasicDBObject longdata = new BasicDBObject("longData", longData);
		BasicDBObject intdata = new BasicDBObject("intData", new BasicDBObject().append("$gt", gt).append("$lte",lte)