1. 개요

NoSQL의 한 종류인 몽고디비(MongoDB)로 다시 돌아오겠다고 약속했던 강철지그입니다. 오늘은 저번에 만든 몽고에 데이터를 넣어보는 시간을 가져보려고 합니다.


2. 접속

몽고디비를 부트하고 나서(mongod) 몽고(mongo)를 실행하여 몽고디비로 진입합니다.


3. 데이터 삽입

그리고 다짜고짜 다름과 같이 뭔가 만들어보았습니다.

$ ./mongo
MongoDB shell version: 2.4.12
connecting to: test
> db.jeeg.insert({"city":"seoul"})
>

성공한 것 같습니다만 혹시 몰라서 로그를 살펴봅니다.

Sat Jan 31 12:58:31.140 [initandlisten] connection accepted from 127.0.0.1:51089 #1 (1 connection now open)
Sat Jan 31 12:59:17.115 [conn1] allocating new ns file ../data/db/test.ns, filling with zeroes...
Sat Jan 31 12:59:17.147 [FileAllocator] allocating new datafile ../data/db/test.0, filling with zeroes...
Sat Jan 31 12:59:17.147 [FileAllocator] creating directory ../data/db/_tmp
Sat Jan 31 12:59:17.220 [FileAllocator] done allocating datafile ../data/db/test.0, size: 64MB,  took 0.072 secs
Sat Jan 31 12:59:17.233 [FileAllocator] allocating new datafile ../data/db/test.1, filling with zeroes...
Sat Jan 31 12:59:17.233 [conn1] build index test.jeeg { _id: 1 }
Sat Jan 31 12:59:17.235 [conn1] build index done.  scanned 0 total records. 0.001 secs
Sat Jan 31 12:59:17.235 [conn1] insert test.jeeg ninserted:1 keyUpdates:0 locks(micros) w:120346 120ms
Sat Jan 31 12:59:17.401 [FileAllocator] done allocating datafile ../data/db/test.1, size: 128MB,  took 0.167 secs

로그는 각자 해석합니다.

이번에는 find() 를 사용합니다.

> db.jeeg.find()
{ "_id" : ObjectId("54cc5315f9b3e67df04fc9e2"), "city" : "seoul" }
>

city는 seoul이 잘 나옵니다. 하나 더 넣어봅니다.

> db.jeeg.insert({"city":"newyork"})
> db.jeeg.find()
{ "_id" : ObjectId("54cc5315f9b3e67df04fc9e2"), "city" : "seoul" }
{ "_id" : ObjectId("54cc54ebf9b3e67df04fc9e3"), "city" : "newyork" }
>

뉴욕도 잘 들어간 것 같습니다.

그럼 이제 두 건을 동시에 insert 해봅니다.

> db.jeeg.insert([{"city":"london"},{"city":"jakarta"}])
> db.jeeg.find()
{ "_id" : ObjectId("54cc5315f9b3e67df04fc9e2"), "city" : "seoul" }
{ "_id" : ObjectId("54cc54ebf9b3e67df04fc9e3"), "city" : "newyork" }
{ "_id" : ObjectId("54cc5664f9b3e67df04fc9e4"), "city" : "london" }
{ "_id" : ObjectId("54cc5664f9b3e67df04fc9e5"), "city" : "jakarta" }
 

 잘 되고 있습니다.

그럼 이번에는 뜬금없이.

> db.jeeg.insert({"_id":0})
> db.jeeg.find()
{ "_id" : ObjectId("54cc5315f9b3e67df04fc9e2"), "city" : "seoul" }
{ "_id" : ObjectId("54cc54ebf9b3e67df04fc9e3"), "city" : "newyork" }
{ "_id" : ObjectId("54cc5664f9b3e67df04fc9e4"), "city" : "london" }
{ "_id" : ObjectId("54cc5664f9b3e67df04fc9e5"), "city" : "jakarta" }
{ "_id" : 0 }

 그리고 또 일괄 insert로, 대신 실패를 유도해 보겠습니다.

> db.jeeg.insert([{"_id":0},{"_id":1}])
E11000 duplicate key error index: test.jeeg.$_id_  dup key: { : 0.0 }
> db.jeeg.find()
{ "_id" : ObjectId("54cc5315f9b3e67df04fc9e2"), "city" : "seoul" }
{ "_id" : ObjectId("54cc54ebf9b3e67df04fc9e3"), "city" : "newyork" }
{ "_id" : ObjectId("54cc5664f9b3e67df04fc9e4"), "city" : "london" }
{ "_id" : ObjectId("54cc5664f9b3e67df04fc9e5"), "city" : "jakarta" }
{ "_id" : 0 }

duplicate key error index가 발생했고 _id:1도 insert 되지 않았습니다.

일단 오늘은 여기까지입니다.