Java操作Mongo


Java操作Mongo

// 創建連接
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
                                      new ServerAddress("localhost", 27018),
                                      new ServerAddress("localhost", 27019)));
//使用mydb數據庫
DB db = mongoClient.getDB( "mydb" );

//獲取所有Collection
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
    System.out.println(s);
}

//獲取特定Collection
DBCollection coll = db.getCollection("testCollection");

//寫入一個Document
BasicDBObject doc = new BasicDBObject("name", "MongoDB")
        .append("type", "database")
        .append("count", 1)
        .append("info", new BasicDBObject("x", 203).append("y", 102));
coll.insert(doc);

//查詢一個Collection中第一個Document
DBObject myDoc = coll.findOne();
System.out.println(myDoc);

//查詢Collection中所有Documents
DBCursor cursor = coll.find();
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

Reference

http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章