環(huán)境配置
在Java程序中如果要使用MongoDB,你需要確保已經(jīng)安裝了Java環(huán)境及MongoDB JDBC 驅(qū)動。
你可以參考本站的 Java教程來安裝Java程序?,F(xiàn)在讓我們來檢測你是否安裝了 MongoDB JDBC 驅(qū)動。
連接數(shù)據(jù)庫,你需要指定數(shù)據(jù)庫名稱,如果指定的數(shù)據(jù)庫不存在,mongo會自動創(chuàng)建數(shù)據(jù)庫。
連接數(shù)據(jù)庫的Java代碼如下:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 連接到 mongodb 服務(wù) MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 連接到數(shù)據(jù)庫 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
現(xiàn)在,讓我們來編譯運行程序并創(chuàng)建數(shù)據(jù)庫test。
你可以更加你的實際環(huán)境改變MongoDB JDBC驅(qū)動的路徑。
本實例將MongoDB JDBC啟動包 mongo-2.10.1.jar 放在本地目錄下:
$javac MongoDBJDBC.java $java -classpath ".:mongo-2.10.1.jar" MongoDBJDBC Connect to database successfully Authentication: true
如果你使用的是Window系統(tǒng),你可以按以下命令來編譯執(zhí)行程序:
$javac MongoDBJDBC.java $java -classpath ".;mongo-2.10.1.jar" MongoDBJDBC Connect to database successfully Authentication: true
如果用戶名及密碼正確,則Authentication 的值為true。
我們可以使用com.mongodb.DB類中的createCollection()來創(chuàng)建集合
代碼片段如下:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 連接到 mongodb 服務(wù) MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 連接到數(shù)據(jù)庫 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.createCollection("mycol"); System.out.println("Collection created successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
編譯運行以上程序,輸出結(jié)果如下:
Connect to database successfully Authentication: true Collection created successfully
我們可以使用com.mongodb.DBCollection類的 getCollection() 方法來獲取一個集合
代碼片段如下:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 連接到 mongodb 服務(wù) MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 連接到數(shù)據(jù)庫 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.createCollection("mycol"); System.out.println("Collection created successfully"); DBCollection coll = db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
編譯運行以上程序,輸出結(jié)果如下:
Connect to database successfully Authentication: true Collection created successfully Collection mycol selected successfully
我們可以使用com.mongodb.DBCollection類的 insert() 方法來插入一個文檔
代碼片段如下:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 連接到 mongodb 服務(wù) MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 連接到數(shù)據(jù)庫 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); BasicDBObject doc = new BasicDBObject("title", "MongoDB"). append("description", "database"). append("likes", 100). append("url", "http://m.hgci.cn/mongodb/"). append("by", "w3cschool.cn"); coll.insert(doc); System.out.println("Document inserted successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
編譯運行以上程序,輸出結(jié)果如下:
Connect to database successfully Authentication: true Collection mycol selected successfully Document inserted successfully
我們可以使用com.mongodb.DBCollection類中的 find() 方法來獲取集合中的所有文檔。
此方法返回一個游標(biāo),所以你需要遍歷這個游標(biāo)。
代碼片段如下:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 連接到 mongodb 服務(wù) MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 連接到數(shù)據(jù)庫 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); DBCursor cursor = coll.find(); int i=1; while (cursor.hasNext()) { System.out.println("Inserted Document: "+i); System.out.println(cursor.next()); i++; } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
編譯運行以上程序,輸出結(jié)果如下:
Connect to database successfully Authentication: true Collection mycol selected successfully Inserted Document: 1 { "_id" : ObjectId(7df78ad8902c), "title": "MongoDB", "description": "database", "likes": 100, "url": "http://m.hgci.cn/mongodb/", "by": "w3cschool.cn" }
你可以使用 com.mongodb.DBCollection 類中的 update() 方法來更新集合中的文檔。
代碼片段如下:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 連接到Mongodb服務(wù) MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 連接到你的數(shù)據(jù)庫 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); DBCursor cursor = coll.find(); while (cursor.hasNext()) { DBObject updateDocument = cursor.next(); updateDocument.put("likes","200") coll.update(updateDocument); } System.out.println("Document updated successfully"); cursor = coll.find(); int i=1; while (cursor.hasNext()) { System.out.println("Updated Document: "+i); System.out.println(cursor.next()); i++; } }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
編譯運行以上程序,輸出結(jié)果如下:
Connect to database successfully Authentication: true Collection mycol selected successfully Document updated successfully Updated Document: 1 { "_id" : ObjectId(7df78ad8902c), "title": "MongoDB", "description": "database", "likes": 200, "url": "http://m.hgci.cn/mongodb/", "by": "w3cschool.cn" }
要刪除集合中的第一個文檔,首先你需要使用com.mongodb.DBCollection類中的 findOne()方法來獲取第一個文檔,然后使用remove 方法刪除。
代碼片段如下:
import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; import com.mongodb.ServerAddress; import java.util.Arrays; public class MongoDBJDBC{ public static void main( String args[] ){ try{ // 連接到Mongodb服務(wù) MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // 連接到你的數(shù)據(jù)庫 DB db = mongoClient.getDB( "test" ); System.out.println("Connect to database successfully"); boolean auth = db.authenticate(myUserName, myPassword); System.out.println("Authentication: "+auth); DBCollection coll = db.getCollection("mycol"); System.out.println("Collection mycol selected successfully"); DBObject myDoc = coll.findOne(); coll.remove(myDoc); DBCursor cursor = coll.find(); int i=1; while (cursor.hasNext()) { System.out.println("Inserted Document: "+i); System.out.println(cursor.next()); i++; } System.out.println("Document deleted successfully"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
編譯運行以上程序,輸出結(jié)果如下:
Connect to database successfully Authentication: true Collection mycol selected successfully Document deleted successfully
你還可以使用 save(), limit(), skip(), sort() 等方法來操作MongoDB數(shù)據(jù)庫。
更多建議: