Skip to content

Instantly share code, notes, and snippets.

@Curookie
Last active November 17, 2021 20:23
Show Gist options
  • Save Curookie/7a3abf9686d386c8bfa5e1c16e8a3060 to your computer and use it in GitHub Desktop.
Save Curookie/7a3abf9686d386c8bfa5e1c16e8a3060 to your computer and use it in GitHub Desktop.
MongoDB.md

기본 shell 명령어

mongo
몽고DB 쉘 실행
use <DB 이름>
데이터 베이스를 사용하려면 관계형 db에서 database를 만들고 table 을 만들어 주는 것과 똑같이 database 를 먼저 만든 후 collection 을 만들어 주면된다. use 명령어를 통해서 db를 만들어준다. 이 database 를 사용하겟다! 라는 느낌 git checkout 같은 느낌.
show dbs
현재 생성되어 있는 db들을 보여준다. use database 를 하자마자 show dbs를 하면 안보이는데 collection 을 만들어 주면 그때부터 보이니 당황하지 마시길.
db
현재의 사용하고 있는 db를 보여준다.
show collections
현재 생성된 collection들을 보여준다.

insert하기
db.person.insert({"nickname":"freekim", "email":"[email protected]"})
document 는 insert 명령어를 통해 json format 으로 insert 한다. 배열의 형태로 넣으려면 [] 를 사용한다. json format 과 똑같다. 아래서 보면 알 수 있듯이 잘 들어갔다.

select하기
db.person.find()

delete하기
db.person.remove({"nickname":"freekim"})

update하기
db.person.update({"nickname":"freekim"}, {"$set": {"email":"[email protected]"}})

  1. upsert:
    가장 많이 사용되는 upsert입니다. update와 insert를 합성한 단어로 만약 matchQuery에서 일치하는 결과가 없는 경우 새로운 값을 추가(insert)할 것인지의 여부를 선택할 수 있습니다. 값은 true / false로 설정하며 기본값은 false입니다.

  2. multi:
    이 값을 multi: true로 설정할 경우 여러개의 일치하는 document(row)가 존재할 경우 모두 변경할 수 있게 됩니다. 기본값은 false이며 하나의 document만 업데이트 합니다.

  3. hint: <document: index>
    hint값을 사용하면 특정 도큐멘트의 인덱스를 사용하여 찾거나 조작하는 것이 가능합니다.

$eq
Matches values that are equal to a specified value.
$gt
Matches values that are greater than a specified value.
$gte
Matches values that are greater than or equal to a specified value.
$in
Matches any of the values specified in an array.
$lt
Matches values that are less than a specified value.
$lte
Matches values that are less than or equal to a specified value.
$ne
Matches all values that are not equal to a specified value.
$nin
Matches none of the values specified in an array.

{ $range: [ 0, 10, 2 ] }
[ 0, 2, 4, 6, 8 ]
 
{ $range: [ 10, 0, -2 ] }
[ 10, 8, 6, 4, 2 ]
 
{ $range: [ 0, 10, -2 ] }
[ ]
 
{ $range: [ 0, 5 ] }
[ 0, 1, 2, 3, 4 ]

{createdAt:{$gte:ISODate(“2020-03-01”),$lt:ISODate(“2021-04-01”)}}

db.collection.find({
    created_at: {
        $gte: ISODate("2015-02-01T00:00:00.000Z"),
        $lt: ISODate("2015-03-03T00:00:00.000Z")
    }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment