最近关注大数据,自然会关注到nosql数据库,其中当然是mongodb。
nosql数据库大多是k,v数据库,这也不是新鲜的名词了,berkerly DB已经存在很多年了,现在属于oracle。
具体k,v数据库为何比传统数据库优载的原理,还需要深入了解和学习。同时两者应该是各有存在的空间。
mongodb的使用非常简单,简单包装一下类如下:
package DBHelper; import com.mongodb.*;
import com.mongodb.util.JSON; import java.net.UnknownHostException;
import java.util.List; /**
* Created by Weijiabin on 2014/10/29.
*/
public class MongoDB { public MongoDB() throws UnknownHostException {
_mongo = new Mongo();
}
private Mongo _mongo;
public DB getDb(String strDbName){
return _mongo.getDB(strDbName);
} public DBCollection getDbCollection(String strStrDbName, String strTableName){
return getDb(strStrDbName).getCollection(strTableName);
} public void add(String strDbName,String strTableName, DBObject obj){
getDbCollection(strDbName,strTableName).save(obj);
} public void addList(String strDbName,String strTableName, List<DBObject> objList){
getDbCollection(strDbName,strTableName).insert(objList);
} public int remove(String strDbName,String strTableName,DBObject obj){
return getDbCollection(strDbName,strTableName).remove(obj).getN();
} public int modify(String strDbName,String strTableName,DBObject objQ,DBObject objN,boolean bUpdateAll){
return getDbCollection(strDbName,strTableName).update(objQ,objN,true,bUpdateAll).getN();
} public DBObject query(String strDbName,String strTableName,DBObject objQ){
return getDbCollection(strDbName,strTableName).findOne(objQ);
} }
测试代码如下:
package DBHelper; import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.junit.Test; import static org.junit.Assert.*; public class MongoDBTest { @Test
public void testGetDb() throws Exception {
MongoDB db = new MongoDB();
BasicDBObject obj = new BasicDBObject();
obj.put("name","weijiabin");
obj.put("sex","man");
obj.put("age",32);
db.add("db1","users",obj); BasicDBObject objQ = new BasicDBObject("age",32); DBObject objR = db.query("db1", "users", objQ);
assertEquals("weijiabin",objR.get("name"));
}
}
看得出来,相当的简单和易用。直接操作json数据结构,有xml的优点,同时比xml更适合网络传输。