安裝mongodb,並啓動,下載mongo-java-driver.jar包。java
直接上代碼
mongodb
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB userdb = client.getDB("test"); DBCollection user = userdb.getCollection("user"); // 添加 System.out.println("--------------添加--------------"); BasicDBObject obj = new BasicDBObject(); obj.append("name", "you know").append("age", 12).append("job", "singer").append("phone", "1234322234") .append("addr", "china"); user.insert(obj); System.out.println(obj.getString("_id")); System.out.println("--------------查詢--------------"); //查詢 BasicDBObject query = new BasicDBObject(); query.append("addr", "china"); DBCursor cursor = user.find(query); while (cursor.hasNext()) { DBObject u = cursor.next(); System.out.println(u.toString()); } //修改 System.out.println("--------------修改--------------"); BasicDBObject q = new BasicDBObject();//查詢條件 q.append("phone", "1234322234"); BasicDBObject o = new BasicDBObject();//修改內容 o.append("job", "java coder"); WriteResult r = user.update(q, o); System.out.println(r.toString()); //刪除 System.out.println("--------------刪除--------------"); WriteResult d = user.remove(q); System.out.println(d.toString()); }
看運行結果shell
--------------添加-------------- 570e4624973e75a9365e9640 --------------查詢-------------- { "_id" : { "$oid" : "570e4624973e75a9365e9640"} , "name" : "you know" , "age" : 12 , "job" : "singer" , "phone" : "1234322234" , "addr" : "china"} --------------修改-------------- { "serverUsed" : "127.0.0.1:27017" , "ok" : 1 , "n" : 1 , "updatedExisting" : true} --------------刪除-------------- { "serverUsed" : "127.0.0.1:27017" , "ok" : 1 , "n" : 0}
代碼很是簡單,能夠看到java 對mongo的操做和在shell上操作很是的相似,但由於java語言自己的緣由,沒法想js等腳本語言那樣簡潔。app
DBObject及其實現類是構建查詢對象和保存對象的關鍵,應該就是構建Bson的關鍵接口、類。spa