1. 개요
MongoDB(몽고DB)에 접속해서 간단한 데이터를 넣는(insert) 예제입니다. 데이터베이스를 선택하고 컬렉션에 문서를 하나 삽입한 뒤, 실제로 생성되었는지 확인해 봅니다.
2. 절차
2-1. MongoDB 접속
$ mongo
MongoDB shell version v3.4.7
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.7
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
Server has startup warnings:
2017-08-21T00:46:56.293+0000 I STORAGE [initandlisten]
2017-08-21T00:46:56.293+0000 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-08-21T00:46:56.293+0000 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-08-21T00:46:56.338+0000 I CONTROL [initandlisten]
2017-08-21T00:46:56.338+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-08-21T00:46:56.338+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2017-08-21T00:46:56.338+0000 I CONTROL [initandlisten]
>
몇 가지 경고가 나오네요. 예제 진행에는 큰 영향이 없으므로 일단 무시합니다. 다만 운영 환경이라면 접근 제어가 비활성화되어 있다는 경고는 반드시 확인해야 합니다.
2-2. 데이터베이스 선택
사용할 데이터베이스 이름은 test_database라고 하겠습니다.
> use test_database switched to db test_database
잘 생성되었는지 DB 목록을 확인합니다.
> show dbs admin 0.000GB local 0.000GB
그런데 내가 만든 test_database가 보이지 않습니다. 그 이유는 아직 아무 데이터도 들어 있지 않기 때문입니다. MongoDB에서는 use로 데이터베이스를 선택해도, 실제 데이터가 저장되기 전까지는 목록에 표시되지 않을 수 있습니다.
어쨌든 현재 선택된 데이터베이스가 test_database가 맞는지 다시 한번 확인합니다.
> db test_database
2-3. 데이터 삽입
이제 데이터를 넣습니다. 아래 예제에서는 emp라는 컬렉션에 이름과 전화번호를 가진 문서(document)를 하나 삽입합니다. 컬렉션이 없으면 삽입 시 자동으로 만들어집니다.
> db.emp.insert({"name":"stdio.h","phone":"010-1234-5678"});
WriteResult({ "nInserted" : 1 })
nInserted 값이 1이면 문서 1건이 정상적으로 삽입되었다는 뜻입니다.
다시 데이터베이스 목록을 확인합니다.
> show dbs admin 0.000GB local 0.000GB test_database 0.000GB >
이번에는 test_database가 목록에 보입니다. 실제로 데이터가 들어갔는지도 확인해 봅니다.
> db.emp.find()
{ "_id" : ObjectId("..."), "name" : "stdio.h", "phone" : "010-1234-5678" }
_id 필드는 MongoDB가 문서를 구분하기 위해 자동으로 추가한 값입니다.