[Bigdata] MongoDB 설치 및 사용 (CRUD로 정리끝!)
저번 시간에는 설치와 시작만 해보았습니다
[Bigdata] 쉽고 간단한 MongoDB 설치방법
1. 설치하기 MongoDB사이트에 접속해 software-community server에 들어갑니다 최신 버전 바로 전에나온 4.2.12를 다운해도 되고 안정적인 버전으로는 3.6.22를 많이 씁니다 (저는 이거로 다운했어요) 2. 환경
memoty.tistory.com
이번에는 이어서 mongo에 접속하고
간단히 CRUD를 실행해보겠습니다
1.Create
빈 db는 보여주지 않기 때문에 처음에 db는 나오지 않았습니다
collection을 생성한 후에는 test 가 생긴게 보이죠?
(test는 db명입니다)
MongoDB Enterprise > use test
switched to db test
MongoDB Enterprise > show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
MongoDB Enterprise > db.createCollection("emp");
{ "ok" : 1 }
MongoDB Enterprise > show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
MongoDB Enterprise > show collections
emp
MongoDB Enterprise >
이제 생성한 emp를 drop을 이용해 다시 지워보겠습니다
MongoDB Enterprise > use test
switched to db test
MongoDB Enterprise > show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
MongoDB Enterprise > db.createCollection("emp");
{ "ok" : 1 }
MongoDB Enterprise > show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
MongoDB Enterprise > show collections
emp
MongoDB Enterprise > db.emp.drop()
true
MongoDB Enterprise > show collections
MongoDB Enterprise > show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
MongoDB Enterprise > db.emp.renameCollection('employee')
{ "ok" : 1 }
MongoDB Enterprise > show collections
employee
(마지막 두 줄에서는 collection(테이블)의 이름을 emp에서 employee로 바꿨습니다)
2.Insert
insert는 이렇게 create한 후에 삽입해도 되지만
아래 update문에 보이는 것처럼 create없이 insert만 해도 생성이 됩니다
MongoDB Enterprise > db.employee.insert({enl:1,ename:'kim',sal:1000})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise > db.employee.find()
{ "_id" : ObjectId("6041da846ebd85f5816150d2"), "enl" : 1, "ename" : "kim", "sal" : 1000 }
MongoDB Enterprise > db.employee.find({},{_id:0}; #조건과 필드(없으면 전부 표시함)
{ "enl" : 1, "ename" : "kim", "sal" : 1000 }
3.Update
db.student.insert가 갑자기 된다고?
create한 적없는 테이블인데??
=> 테이블을 만들지 않아도 insert문 만으로도 컬렉션이 만들어집니다 (바로 위에서 말한거 요겁니다!)
마지막 줄에는 sno가 2인 필드의 name을 'park'으로 수정했습니다
MongoDB Enterprise > db.student.insert({sno:1,name:'김몽고', major:'컴공'})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise > show collections
employee
student
MongoDB Enterprise > db.student.insert({sno:2,name:'kim',score:95})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise > db.student.find()
{ "_id" : ObjectId("6041dc12aa27402d0511633e"), "sno" : 1, "name" : "김몽고", "major" : "컴공" }
{ "_id" : ObjectId("6041dc6baa27402d0511633f"), "sno" : 2, "name" : "kim", "score" : 95 }
MongoDB Enterprise > db.student.update({sno:2},{$set:{name:'park'}}) #수정방법
필드를 아예 만들지 않고 일부 필드명이 달라도 (major 와 score)
아무 문제없이 추가가 가능합니다
4. Drop
MongoDB Enterprise > db.student.remove({sno:1})
WriteResult({ "nRemoved" : 1 })
MongoDB Enterprise > db.student.find()
{ "_id" : ObjectId("6041dc6baa27402d0511633f"), "sno" : 2, "name" : "kim", "score" : 95 }
MongoDB Enterprise > db.student.drop()
true
MongoDB Enterprise > show collections
employee
잘못 입력했을때 cmd창을 닫아야 할 상황이 생겨서 당황했었는데
cmd로 연 서버가 닫혀도 저장이 된 상태이므로 다시 열면 데이터가 그대로 있습니다(휴 ^▽^;)