mongoDB 쉘 명령어 검색이 넘 귀찮다.😇
여기에 자주 쓰는 명령어들은 모아둬야지!
> use [dbname]
[dbname]이라는 DB를 생성해주거나 [dbname]로 Switching 해준다
> db.collection.insert(
[document or array of documents],
{
writeConcern: [document],
ordered: [boolean] # true면 document array의 인덱스 순으로 insert. default는 True
}
)
WriteResult({ "nInserted" : 1 })
document 하나를 insert하면 collection이 함께 생성된다.
> show dbs
local 0.000GB
dotori 0.070GB
> db
dotori
worktime
> show collections
items
users
adminsettings
> db.getCollectionNames()
["items", "users", "adminsettings"]
> 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
}
> db.[collection].find([query],[projection])
find() 메소드를 사용하여 collection 내의 document를 select 한다.
| Parameter | Type | Description |
|---|---|---|
| query | Document | Option. Document를 Select 할 기준 |
| projection | Document | Option. Document select 결과에 포함될 fields |
> 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"
]
}
> 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}
... )
| Operator | Meaning |
|---|---|
| $eq | equals |
| $gt | greater than |
| $gte | greater than or equals |
| $lt | less than |
| $lte | less than or equals |
| $ne | not equal |
| $in | in an array |
| $nin | not in an array |
db.books.find(
{ $or: [ { price: { $lt: 200 } }, { stock: 0 } ] }
)
> db.[collection].update(
[query],
[update],
{
upsert: [boolean], # true 일 때, query에 매칭되는 document가 없으면 새로 insert
multi: [boolean], # false 일 때, 하나만 update
writeConcern: [document]
}
)
db.books.update(
{ price: { $gt: 200 } },
{ $set: { author: "Kim" } },
{ multi: true }
)
price가 200보다 큰 document를 찾아, author를 kim으로 바꿔주는 명령
| Operator | Description |
|---|---|
| $inc | field의 value를 지정한 수만큼 증가시킨다. |
| $rename | field 이름을 rename한다. |
| $setOnInsert | update()의 upsert가 true로 설정되었을 경우, document가 insert될 때의 field value를 설정한다. |
| $set | update할 field의 value를 설정한다. |
| $unset | document에서 설정된 field를 삭제한다 |
| $min | 설정값이 field value보다 작은 경우만 update한다. |
| $max | 설정값이 field value보다 큰 경우만 update한다. |
| $currentDate | 현재 시간을 설정한다 |
> db.dropDatabase();
{ "dropped" : "dotori", "ok" : 1 }
db.items.drop()
> db.collection.remove(
[query],
{
justOne: [boolean],
writeConcern: [document]
}
)
> db.collection.update(
[query],
{
$unset:{fieldname:1}
}
)