데이터베이스 관리
1. 데이터베이스 목록 출력
show dbs
2. 사용 데이터베이스 변경
db=db.getSiblingDB('testDB')
use testDB
3. 데이터베이스 생성
use newDB
db.createCollection("newCollection")
4. 데이터베이스 삭제
use newDB db.dropDatabase()
5. 데이터베이스 복사
db.copyDatabase('customers', 'customers_archive')
컬렉션 관리
1. 컬렉션 목록 출력
use test show collections
2. 컬렉션 생성
createCollection(name, [option]) options properties - capped, autoIndexID, size, max
use testDB
db.createCollection("newCollection", {capped: false})
3. 컬렉션 삭제
use testDB
show collections
col1 = db.getCollection("newCollection")
col1.drop()
show collections
4. 컬렉션에서 문서 검색
find(query) query 는 {key : value}
use testDB
col1 = db.getCollection("newCollection")
col1.find()
col1.find( { speed: "120mph" } )
5. 컬렉션에 문서 추가
insert( document ) / save( document )
use testDB
col1 = db.getCollection( "newCollection")
col1.find()
col1.insert( { vehicle : "plane" , speed: "480mph" } )
col1.insert( { vehicle : "car" , speed: "120mph" } )
col1.insert( { vehicle : "train" , speed: "220mph" } )
col1.find()
6. 컬렉션에서 문서 삭제
remove(document) or Document 가 없으면 모두 삭제
use testDB
col1 = db.getCollection("newCollection")
col1.find()
col1.remove( { vehicle: "plane" } )
col1.find()
col1.remove()
col1.find()
7. 컬렉션의 문서를 갱신
save(object) or update(query, update, options) $inc는 필드의 값을 증가시키고, $set은 필드의 값을 설정하고, $push는 요소를 배열에 추가한다. 따라서 갱신 객체는 하나의 필드를 증가시키고, 또 다른 필드의 값을 설정하며, 세번째 필드의 이름을 변경
{ $inc: {count:1},
$set: {name: "New Name"},
$rename: {"nickname": "alias"} }
options 파라미터는 Boolean 값이 multi와 upsert 프로퍼티를 갖는 객체
- upsert가 true라면, 문서를 찾을 수 없는 경우 새로운 문서가 생성
- multi가 true라면, 질의와 일치하는 모든 문서를 갱신
- 그렇지 않은 경우에는 첫번째 문서만 갱신
use testDB
col1 = db.getCollection("newCollection")
col1.find()
col1.update(
{speed: "120mph"},
{$set: {speed: "150mph", updated: true}},
{upsert: false, multi: true}
)
col1.save( { "_id" : ObjectId("52a0caf33...ddb"),
"vehicle" : "plane", "speed": "500mph" } )
col1.find()