1. Database
1.1 Create Database
1
USE dss
- dss라는 이름의 데이터 베이스 생성
1
db
- 현재 사용중인 데이터 베이스 확인
1
SHOW dbs
- Database List 확인
- 데이터 베이스를 생성 후에 최소 1개 이상의 Document를 추가해야 생성된 데이터 베이스가 보임
1
2
USE dss
db.user.insert({'name' : 'alice', 'age':'20','email':'alice@gmail.com'})
- Document 생성
- dss 데이터베이스에 user커넥션에 alice라는 user의 정보를 insert함
1.2 Delete Database
1
db.dropDatabase()
- 현재 사용중인 데이터 베이스 삭제
2. Collection
2.1 Create Collection
1
db.createCollection(name, [option])
- Name : Collection 이름
- Option
Capped : True로 설정하면 Collection의 최대 용량을 설정최대 용량의 크기는 Size 옵션으로 설정), 설정된 최대용량 이상으로 데이터가 입력되면 오래된 데이터부터 자동으로 삭제됨
Autoindex : True로 설정하면 _id 필드에 Index가 자동으로 생성
Size : 숫자 데이터를 사용하며 Collection의 최대 사이즈를 byte 단위로 지정
Max : 숫자 데이터를 사용하여 최대 Document 갯수를 설정
1
db.createCollection('user')
- User Collection 생성
1
2
db.createCollection('info1', {autoIndex:true, capped:true, size : 500, max:5})
db.createCollection('info2', {autoIndex:true, capped:true, size : 50, max:5})
- AutoIndex와 Max 옵션을 설정하여 info 컬렉션을 생성
1
db.articles.insert({'title' : 'data science', 'contents':'mongodb'})
- createCollection을 사용하지 안호 articel 컬렉션을 생성
1
show collection
- 컬렉션 리스트 확인
2.2 Delete Collection
1
d.articles.drops()
- Articles 컬렉션 삭제
3. Document
3.1 Make Document
1
db.<collection_name>.insert(<document>)
- Document를 생성하는 법
1
2
3
db.info1.insert({'subject' : 'python', 'level' : 3})
db.info1.insert({'subject' : 'web', 'level' : 1})
db.info1.insert({'subject' : 'sql', 'level' : 2})
- info 컬렉션에 Document 추가
1
2
3
4
5
6
7
8
db.info1.insert([
{'subject' : 'python' , 'level':3},
{'subject' : 'web' , 'level':1},
{'subject' : 'sql' , 'level':2},
{'subject' : 'python' , 'level':3},
{'subject' : 'web' , 'level':1},
{'subject' : 'sql' , 'level':2},
])
- 한번에 여러개의 Document 추가
- max : 5 옵션 제한에 걸려 5개의 데이터가 info1에 들어감
1
2
3
4
5
6
7
db.info2.insert([
{'subject' : 'python' , 'level':3},
{'subject' : 'web' , 'level':1},
{'subject' : 'sql' , 'level':2},
{'subject' : 'python' , 'level':3},
{'subject' : 'web' , 'level':1},
])
- 한번에 여러개의 Document 추가
- size : 50 옵션 제한에 걸려 4개의 데이터가 info2에 입력됨
1
2
3
4
5
6
7
8
db.info.insert([
{'subject' : 'python' , 'level':3},
{'subject' : 'web' , 'level':1},
{'subject' : 'sql' , 'level':2},
{'subject' : 'java' , 'level':3},
{'subject' : 'html' , 'level':1},
{'subject' : 'css' , 'level':2},
])
- info 컬렉션에 6개의 데이터를 입력
3.2 Delete Document
1
db.info.remove({level:2})
- remove를 사용하여 Document 삭제
- level2인 데이터 삭제
- 제약조건이 걸려있는 컬렉션이 도큐먼트는 삭제가 안됨