mongoDB - java 코드에서 insert 명령 수행해보기
try
{
/* MongoDB connection and insert example : kkyunjjang */
Mongo m = new Mongo("localhost");
DB db = m.getDB("test");
Set<String> colls = db.getCollectionNames();
for(String s:colls) // print collections name
{
System.out.println(s);
}
DBCollection coll = db.getCollection("users");
BasicDBObject doc = new BasicDBObject();
doc.put("name", "kim");
doc.put("age", 28);
doc.put("status", "A");
doc.put("groups", "dreamwiz");
coll.insert(doc);
// check your mongodb at shell
} catch(UnknownHostException e)
{
System.out.println("Unknown Host!!");
}
컴파일 / run 후에
shell 환경에서 mongoDB에 접속하여 확인해보면 데이터가 들어가 있다.
collection이 없는경우에는 자동으로 생성해주니 오타에 조심하자. (대소문자에도 엄격하므로 주의할 것)