本文介绍java如何对MongoDB数据库进行CRUD操作。
1、测试环境
(1) OS:windows XP (2) DataBase:MongoDB V 1.8.1 (3) Driver:mongo-2.6.5.jar (4) Test:junit-4.10.jar2、初始化连接
private Mongo mongo = null; private DB db = null; private DBCollection dbCollection = null; @Before public void init(){ try { mongo = new Mongo("localhost",27017); db = mongo.getDB("test"); dbCollection = db.getCollection("emp"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } }上述代码是连接MongoDB数据库的,基本上分为三步:
(1)建立连接 (2)获取要操作的数据库实例 (3)获取要操作的集合实例
3、关闭连接
@After public void destroy(){ if(mongo != null){ mongo.close(); mongo = null; db = null; dbCollection = null; }4、CRUD操作
(1)C---插入记录
/** * 插入10条记录 * 指定_id */ @Test public void testCreate(){ DBObject obj = null; for(int i=1;i<=10;i++){ obj = new BasicDBObject("_id",i).append("name", "yy"+i).append("age", i*10); dbCollection.save(obj); } }插入新的记录时,上述代码使用的是save接口。
(2)R—查询所有记录
@Test public void testReadAll(){ DBCursor cursor = dbCollection.find(); while(cursor.hasNext()){ System.out.println(cursor.next()); } }结果如下:
{ "_id" : 1 , "name" : "yy1" , "age" : 10} { "_id" : 2 , "name" : "yy2" , "age" : 20} { "_id" : 3 , "name" : "yy3" , "age" : 30} { "_id" : 4 , "name" : "yy4" , "age" : 40} { "_id" : 5 , "name" : "yy5" , "age" : 50} { "_id" : 6 , "name" : "yy6" , "age" : 60} { "_id" : 7 , "name" : "yy7" , "age" : 70} { "_id" : 8 , "name" : "yy8" , "age" : 80} { "_id" : 9 , "name" : "yy9" , "age" : 90} { "_id" : 10 , "name" : "yy10" , "age" : 100}(3) R—根据主键ID查询记录
@Test public void testReadOneWithId(){ DBObject obj = dbCollection.findOne(new BasicDBObject("_id",1)); System.out.println(obj); }结果如下:
{ "_id" : 1 , "name" : "yy1" , "age" : 10}( 4)R—模糊查询
@Test public void testReadPuzzy(){ Pattern pattern = Pattern.compile("^yy1"); BasicDBObject obj = new BasicDBObject("name",pattern); DBCursor cursor = dbCollection.find(obj); while(cursor.hasNext()){ System.out.println(cursor.next()); } }模糊查询使用到了正则表达式。
结果如下:
{ "_id" : 1 , "name" : "yy1" , "age" : 10} { "_id" : 10 , "name" : "yy10" , "age" : 100}(5) U—修改记录
@Test public void testUpdate(){ BasicDBObject condition = new BasicDBObject("_id",10); BasicDBObject res = new BasicDBObject("name","yy10_new"); BasicDBObject res2 = new BasicDBObject("$set",res); //若没有此语句,直接调用下面的语句,返回结果{ "_id" : 10 , "name" : "yy10_new"} dbCollection.update(condition, res2); System.out.println(dbCollection.findOne(new BasicDBObject("_id",10))); }结果如下:
{ "_id" : 10 , "age" : 100 , "name" : "yy10_new"}(6) D—删除记录
@Test public void testDelete(){ dbCollection.remove(new BasicDBObject("_id",10)); testReadAll(); }结果如下:
{ "_id" : 1 , "name" : "yy1" , "age" : 10} { "_id" : 2 , "name" : "yy2" , "age" : 20} { "_id" : 3 , "name" : "yy3" , "age" : 30} { "_id" : 4 , "name" : "yy4" , "age" : 40} { "_id" : 5 , "name" : "yy5" , "age" : 50} { "_id" : 6 , "name" : "yy6" , "age" : 60} { "_id" : 7 , "name" : "yy7" , "age" : 70} { "_id" : 8 , "name" : "yy8" , "age" : 80} { "_id" : 9 , "name" : "yy9" , "age" : 90}