標籤:exception oca localhost 串連 lease document cdb 操作 輸出
準備工作:
下載好mongodriver.jar包(https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver/3.6.1/)
代碼實現:
try {
// 執行個體化Mongo對象,串連27017連接埠
Mongo mongo = new Mongo("localhost", 27017);
// 串連名為yourdb的資料庫,假如資料庫不存在的話,mongodb會自動建立
DB db = mongo.getDB("test");
// Get collection from MongoDB, database named "yourDB"
// 從Mongodb中獲得名為yourColleection的資料集合,如果該資料集合不存在,Mongodb會為其建立立
DBCollection collection = db.getCollection("test1");
// 使用BasicDBObject對象建立一個mongodb的document,並給予賦值。
BasicDBObject document = new BasicDBObject();
//document.put("id", 1001);
//document.put("msg", "hello world mongoDB in Java");
// 將建立立的document儲存到collection中去
//collection.insert(document);
// 建立要查詢的document
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "chen");
// 使用collection的find方法尋找document
DBCursor cursor =collection.find(searchQuery);
// 迴圈輸出結果
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println("Hello World");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
java對mongodb資料庫的簡單操作