- 간단하게 java로 mongoDB 테스트

1. MongoDB  2.0.2
2. MongoDB-Java-Driver 2.5.2
3. JDK 1.6
4. Maven  3.0.3
5. STS (SpringSource Tool Suite Version: 2.8.1.RELEASE)

1. Java Project 생성

2012:01:30 09:04:20



2. eclipse 포멧으로 변환??

2012:01:30 09:06:28



3.  STS  에 임포트


4. 샘플 코드


package com.jeonguk.core;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * Java + MongoDB Hello world Example
 * Hello world!
 *
 */
public class App {
    public static void main( String[] args ) {
       
    try {
   
    // connect to mongoDB, ip and port number
    Mongo mongo = new Mongo("localhost",27017);
   
    // get database from MongoDB,
    // if database doesn't exists, mongoDb will create  it automatically
    DB db = mongo.getDB("jeongukdb");
   
    // Get collection from MongoDB, database named "jeongukdb"
    // if collection doesn't exists, mongoDB will create it automatically
    DBCollection collection = db.getCollection("jeongukCollection");
   
    // create a document to store key and value
    BasicDBObject document = new BasicDBObject();
    document.put("id", 1001);
    document.put("msg", "Hello World mongoDB in Java 2222");
   
    // save it into collection named "jeongukCollection"
    collection.insert(document);
   
    // search query
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("id", 1001);
   
    // query it
    DBCursor cursor = collection.find(searchQuery);
   
    // loop over the cursor and display the retrieved result
    while (cursor.hasNext()) {
    System.out.println(cursor.next());
    }
   
    System.out.println("Done");
   
    } catch (UnknownHostException e) {
    e.printStackTrace();
    } catch (MongoException e) {
    e.printStackTrace();
    }
   
   
    }
}




Result :

{ "_id" : { "$oid" : "4f25e1df9e0e6a92c6fe5e0a"} , "id" : 1001 , "msg" : "Hello World mongoDB in Java"}
Done




 
신고
Posted by jeonguk