該樣本基於當前最新的mongo驅動,版本為mongo-2.10.1.jar,用junit寫的單元測試。
TestCase.java Java代碼 package com.wujintao.mongo; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import org.junit.Test; import com.mongodb.AggregationOutput; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MapReduceCommand; import com.mongodb.MapReduceOutput; import com.mongodb.Mongo; import com.mongodb.QueryBuilder; import com.mongodb.WriteConcern; public class TestCase { //DBCursor cursor = coll.find(condition).addOption(Bytes.QUERYOPTION_NOTIMEOUT);//設定遊標不要逾時 @Test /** * 擷取所有資料庫執行個體 */ public void testGetDBS() { List<String> dbnames = MongoUtil.getMong().getDatabaseNames(); for (String dbname : dbnames) { System.out.println("dbname:" + dbname); } } @Test /** * 刪除資料庫 */ public void dropDatabase() { MongoUtil.getMong().dropDatabase("my_new_db"); } @Test /** * 查詢所有表名 */ public void getAllCollections() { Set<String> colls = MongoUtil.getDB().getCollectionNames(); for (String s : colls) { System.out.println(s); } } @Test public void dropCollection() { MongoUtil.getColl("jellonwu").drop(); } /** * 添加一條記錄 */ @Test public void addData() { DBCollection coll = MongoUtil.getColl("wujintao"); 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); coll.insert(doc); // 設定write concern,以便操作失敗時得到提示 coll.setWriteConcern(WriteConcern.SAFE);