[MongoDB] 쉘 Command 모음

배채윤·2020년 10월 26일

mongoDB 쉘 명령어 검색이 넘 귀찮다.😇
여기에 자주 쓰는 명령어들은 모아둬야지!

1. Create

(1) DB

> use [dbname]

[dbname]이라는 DB를 생성해주거나 [dbname]로 Switching 해준다

(2) Collection&Document

> db.collection.insert(
  [document or array of documents],
  {
    writeConcern: [document],
    ordered: [boolean] # true면 document array의 인덱스 순으로 insert. default는 True
  }
)

WriteResult({ "nInserted" : 1 })

document 하나를 insert하면 collection이 함께 생성된다.

2. Read

(1) DB

> show dbs
local		0.000GB
dotori		0.070GB

> db
dotori
worktime

(2) Collection

> show collections
items
users
adminsettings

> db.getCollectionNames()
["items", "users", "adminsettings"]

(3) 기타

  • 용량 확인
> use [dbname]
> db.stats()
{
	"db" : "test",
	"collections" : 0,
	"views" : 0,
	"objects" : 0,
	"avgObjSize" : 0,
	"dataSize" : 0,
	"storageSize" : 0, # 실제 크기
	"numExtents" : 0,
	"indexes" : 0,
	"indexSize" : 0,
	"scaleFactor" : 1,
	"fileSize" : 0,
	"fsUsedSize" : 0,
	"fsTotalSize" : 0,
	"ok" : 1
}

(3) Document

  • find() 메소드
> db.[collection].find([query],[projection])

find() 메소드를 사용하여 collection 내의 document를 select 한다.

ParameterTypeDescription
queryDocumentOption. Document를 Select 할 기준
projectionDocumentOption. Document select 결과에 포함될 fields

  • collection 내 모든 document select
> db.items.find()
{ "_id" : ObjectId("5f963733a7540da231c3e759"), "author" : "test", "title" : "test", "tags" : [ "rttt", "maya", "texture", "scene" ]}

> db.items.find().pretty() # 정리해서 출력
{
	"_id" : ObjectId("5f963733a7540da231c3e759"),
	"author" : "test",
	"title" : "test",
	"tags" : [
		"rttt",
		"maya",
		"texture",
		"scene"
	]
}

  • query, field 작성 예시
> db.items.find(
... {title:"test"},
... {_id:0,title:1,tag:1}
... )

{ "title" : "test", "tags" : [ "rttt", "maya", "texture", "scene" ] }

  • 비교 연산자
> db.books.find(
... {price:{$gt:100,$lte:400}},
... {_id:0,title:1,tag:1}
... )
OperatorMeaning
$eqequals
$gtgreater than
$gtegreater than or equals
$ltless than
$lteless than or equals
$nenot equal
$inin an array
$ninnot in an array

  • 논리 연산자
db.books.find(
  { $or: [ { price: { $lt: 200 } }, { stock: 0 } ] }
)

3. Update

> db.[collection].update(
  [query],
  [update],
  {
   upsert: [boolean], # true 일 때, query에 매칭되는 document가 없으면 새로 insert 
   multi: [boolean],  # false 일 때, 하나만 update
   writeConcern: [document]
  }
)

writeConcern

  • 예시
db.books.update(
  { price: { $gt: 200 } },
  { $set: { author: "Kim" } },
  { multi: true }
)

price가 200보다 큰 document를 찾아, author를 kim으로 바꿔주는 명령

  • Update field Operators
OperatorDescription
$incfield의 value를 지정한 수만큼 증가시킨다.
$renamefield 이름을 rename한다.
$setOnInsertupdate()의 upsert가 true로 설정되었을 경우, document가 insert될 때의 field value를 설정한다.
$setupdate할 field의 value를 설정한다.
$unsetdocument에서 설정된 field를 삭제한다
$min설정값이 field value보다 작은 경우만 update한다.
$max설정값이 field value보다 큰 경우만 update한다.
$currentDate현재 시간을 설정한다

4. Delete

(1) DB

> db.dropDatabase();
{ "dropped" : "dotori", "ok" : 1 }

(2) Collection

db.items.drop()

(3) Document

> db.collection.remove(
  [query],
  {
    justOne: [boolean],
    writeConcern: [document]
  }
)

(4) Field

> db.collection.update(
   [query],
    {
      $unset:{fieldname:1}
      }
)

Reference

profile
새로운 기술을 테스트하고 적용해보는 걸 좋아하는 서버 개발자

0개의 댓글