1、先下载mongodb-java-driver 目前最新版本是2.9.3
2、下面是基本的CRUD示例代码:
1 package MongoDB; 2 3 import com.mongodb.BasicDBObject; 4 import com.mongodb.DB; 5 import com.mongodb.DBCollection; 6 import com.mongodb.DBCursor; 7 import com.mongodb.DBObject; 8 import com.mongodb.Mongo; 9 import java.net.UnknownHostException; 10 import java.util.Set; 11 12 import org.junit.Test; 13 14 public class TestMongoDBDriver { 15 16 @Test 17 public void testCRUD() throws UnknownHostException { 18 // 连接到mongodb 19 Mongo mongo = new Mongo("localhost", 27017); 20 21 // 打开数据库test 22 DB db = mongo.getDB("test"); 23 24 // 遍历所有集合的名字 25 Set<String> colls = db.getCollectionNames(); 26 for (String s : colls) { 27 System.out.println(s); 28 // 先删除所有Collection(类似于关系数据库中的"表") 29 if (!s.equals("system.indexes")) { 30 db.getCollection(s).drop(); 31 } 32 } 33 34 // 取得集合emp(若:emp不存在,mongodb将自动创建该集合) 35 DBCollection coll = db.getCollection("emp"); 36 37 // delete all 38 DBCursor dbCursor = coll.find(); 39 for (DBObject dbObject : dbCursor) { 40 coll.remove(dbObject); 41 } 42 43 // create 44 BasicDBObject doc = new BasicDBObject("name", "杨俊明").append("sex", "男") 45 .append("address", 46 new BasicDBObject("postcode", "201202").append( 47 "street", "田林路888号").append("city", "上海")); 48 coll.insert(doc); 49 50 // retrieve 51 BasicDBObject docFind = new BasicDBObject("name", "杨俊明"); 52 DBObject findResult = coll.findOne(docFind); 53 System.out.println(findResult); 54 55 // update 56 doc.put("sex", "MALE");// 把sex属性从"男",改成"MALE" 57 coll.update(docFind, doc); 58 findResult = coll.findOne(docFind); 59 System.out.println(findResult); 60 61 coll.dropIndexes();// 先删除所有索引 62 // create index 63 coll.createIndex(new BasicDBObject("name", 1)); // 1代表升序 64 } 65 66 }
延伸阅读:
mondodb-java-driver 官方在线文档