java對mongodb資料庫的簡單操作

來源:互聯網
上載者:User

標籤: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資料庫的簡單操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.