標籤:
我們總不能一直使用cmd對資料庫操作,資料庫總是要在程式中使用的。今天來說一下怎麼通過Java調用MongoDB。
學習一下最基本也是最常用的增刪查改語句,這是使用資料庫的基礎。
注意事項:
1、要開啟mongod.exe,程式運行期間要一直開著。
2、Java項目裡面要匯入mongo的jar包,mongo-版本號碼-jar。
以下為代碼:
public class MongoTest { public static void main(String args[]) throws UnknownHostException, MongoException{ //建立了一個MongoDB的資料庫連接對象,它預設串連到當前機器的localhost地址,連接埠是27017 Mongo mongo = new Mongo(); //獲得了一個mydbs的資料庫,如果該資料庫不存在則會建立 DB db = mongo.getDB("mydbs"); //擷取mydbs這個資料庫中的資料庫表! DBCollection mydbs = db.getCollection("mydbs"); //以上對應cmd語句 :use mydbs //在花括弧內的內容就是一個BasicDBObject //如{"name":"binbin"} 就是 BasicDBObject("name","binbin") //再如{"age":{$lte:50}} 就是 BasicDBObject("age", new BasicDBObject("$lte",50)) //一:基本查詢,對應語句:db.mydbs.find() //將尋找的結果返回到遊標中 DBCursor cur = mydbs.find(); //如果有資料則輸出 while (cur.hasNext()) { System.out.println(cur.next()); } //二:插入語句,對應語句:db.mydbs.insert(user) DBObject user = new BasicDBObject(); user.put("name", "weizhibin"); user.put("age", "20"); user.put("school", "uestc"); mydbs.insert(user); //三:刪除語句,對應語句:db.mydbs.remove({"name":"weizhibin"}) mydbs.remove(new BasicDBObject("name","weizhibin")); //四:更新語句,對應語句:db.col.update({"name":"weizhibin"},{$set:{"name":"binbin"}}) mydbs.update(new BasicDBObject("name","weizhibin"),new BasicDBObject("$set",new BasicDBObject("name","bibin"))); //五:條件查詢,對應語句:db.mydbs.find({"name":"weizhibin"}) DBCursor cur2 = mydbs.find(new BasicDBObject("name","weizhibin")); //如果有資料則輸出 while (cur2.hasNext()) { System.out.println(cur2.next()); } }}
好了,以上是最常用的基本增刪查改語句。MongoDB有一些複雜的語句,都是在這些的基礎之上延伸的,學起來也不難,在此就不一一列舉了。
少量代碼帶你熟悉MongoDB在Java下的增刪查改