본문 바로가기

Development/Web & Server

[Mongo DB] Java Driver 사용하기

1. 라이브러리 추가하기~!


<dependency>

<groupId>org.mongodb</groupId>

<artifactId>mongo-java-driver</artifactId>

<version>2.11.3</version>

</dependency>


2. DB 연결하기~!


MongoClient client = new MongoClient("localhost", 27017);
DB db = client.getDB("testPlayMongDB");


3. 데이터 추가~!


final DBCollection collection = db.getCollection("testCollection"); final BasicDBObject basicObject = new BasicDBObject(); basicObject.put("key","value"); collection.insert(basicObject);


4. 데이터 조회


final DBCollection collection = this.mDB.getCollection("testCollection");
final DBCursor cursor = collection.find();

while (cursor.hasNext()) {
      final DBObject object = cursor.next();
      System.out.println(object);
}//end while

cursor.close();