mongodb 주요 명령어 모음
Post

mongodb 주요 명령어 모음

mongodb 계층 구조

DB > COLLECTION(Table) > DOCUMENT(Record)

mongodb 제어 명령어

mongodb 콘솔 실행

1
mongo

mongodb 서버 시작

1
mongod

DB 제어 명령어

전체 DB 조회

1
show dbs

현재 사용 중인 DB 조회

1
db

COLLECTION 제어 명령어

collection 목록 조회

1
show collections

collection 생성

1
db.createCollection("books")

collection 삭제

특정 콜렉션을 삭제한다.

1
db.[collection name].drop()

DOCUMENT 제어 명령어

insert

만약 collection이 없는 경우 collection이 자동 생성되며 값이 입력된다.

1
db.books.insert({"name": "river", "page":312}) 

find

  • books 콜렉션의 데이터 전체를 조회한다.
    1
    
    db.books.find() ;
    
  • page가 400이하인 항목을 검색한다.
    1
    
    db.books.find({"page":{$lte:400} })
    
  • 논리 연산자 검색
    1
    
    db.books.find({ $or: [ { “title”: “article01” }, { “writer”: “Alpha” } ] })
    
  • 정규 표현식 검색
    1
    
    db.books.find( { "title" : /article0[1-2]/ } )
    
  • 출력 할 갯수를 2개로 제한하기
    1
    
    db.books.find().limit(2)
    
  • 2개의 데이터를 생략하고 그 다음부터 출력
    1
    
    db.books.find().skip(2) 
    
  • 특정 컬럼만 조회
    1
    
    db.books.find({}, {title:1})
    
  • 특정 컬럼만 제외하고 조회
    1
    
    db.books.find({}, {title:0})
    
  • 특정 컬럼이 Array 일때 갯수가 1이상인 조건으로 조회
    1
    
    db.users.find({"skills.1": {$exists: true}})
    

update

  • 이름이 Tony면 age를 20으로 변경한다. (단건 처리)
    1
    
    db.user.update( { name: "Tony" }, { $set: { age: 20 } } )
    
  • 다건 처리 시는 multi 옵션을 붙여주거나 updateMany를 사용한다.
    1
    2
    
    db.user.update( { name: "Tony" }, { $set: { age: 20 } }, { multi: true } )
    db.user.updateMany( { name: "Tony" }, { $set: { age: 20 } } )
    
  • 이름이 David이면 score field를 제거한다.
    1
    
    db.user.update( { name: "David" }, { $unset: { score: 1 } } ) 
    
  • 이름이 Charlie이면 skills 배열 중 “angularjs” 와 “java” 를 제거한다.
    1
    
    db.user.update( { name: "Charlie" }, { $pull: { skills: { $in: ["angularjs", "java" ] } } } ) 
    

remove

이름이 tony 이면 삭제한다.

1
db.user.remove({"name":"tony"})