[MongoDB] 기초 실습

hahaha·2021년 11월 13일

DB

목록 보기
3/3

서버 접속

> mongo

DB

생성: use

> use mongodb_sample

# 현재 사용중인 DB 확인
> db

# DB 리스트 확인
> show dbs

  • 최소 한 개의 Document를 추가해야 DB 리스트에서 확인 가능

제거: db.dropDatabase()

> use mongodb_sample

> db.dropDatabase();

Collection

생성: db.createCollection()

option

> use test

# 옵션 없이 생성
> db.createCollection("books")

# 옵션과 함께 생성
> db.createCollection("articles", {
... capped: true,
... autoIndex: true,
... size: 6142800,
... max: 10000
... })

# document를 추가하면서 자동으로 생성
> db.people.insert({"name": "velopert"})

# collection 리스트 확인
> show collections

제거: db.[collection 이름].drop()

> use test

> db.people.drop()

Document

추가: db.[collection 이름].insert(document)

> use books

> db.books.insert({"name": "NodeJS Guide", "author": "Velopert"})

> db.books.insert([
... {"name": "Book1", "author": "Velopert"},
... {"name": "Book2", "author": "Velopert"}
... ]);

# document 리스트 확인
> db.books.find()

제거: db.[collection 이름].remove(criteria, justOne)

매개변수

> db.books.find({"name": "Book1"})

> db.books.remove({"name": "Book1"})

> db.books.find()

조회: db.[collection 이름].find(query, projection)

매개변수

반환값: cursor

  • cursor를 사용하여 데이터 sort 가능
  • 10분 동안 사용되지 않으면 만료됨
# 데이터 추가
> db.articles.insert([
    {
        "title" : "article01",
        "content" : "content01",
        "writer" : "Velopert",
        "likes" : 0,
        "comments" : [ ]
    },
    {
        "title" : "article02",
        "content" : "content02",
        "writer" : "Alpha",
        "likes" : 23,
        "comments" : [
                {
                        "name" : "Bravo",
                        "message" : "Hey Man!"
                }
        ]
    },
    {
        "title" : "article03",
        "content" : "content03",
        "writer" : "Bravo",
        "likes" : 40,
        "comments" : [
                {
                        "name" : "Charlie",
                        "message" : "Hey Man!"
                },
                {
                        "name" : "Delta",
                        "message" : "Hey Man!"
                }
        ]
    }
])

# 모든 document 조회
> db.articles.find*(

# document 깔끔하게 이쁘게 조회
> db.articles.find().pretty()

# 특정 조건을 만족하는 document 조회
# 1. writer 값이 "Velopert"인
> db.articles.find({"writer": "Velopert"}).pretty()

# 2. likes 값이 30 이하인
> db.articles.find({"likes": {$lte: 30}}).pretty()

# projection 매개변수 활용
# 쿼리의 결과값에서 보여질 field 설정
> db.articles.find( { } , { "_id": false, "title": true, "content": true } )

MongoDB Query 연산자

  • $eq: equals
  • $ne: not equals
  • $gt: greater then
  • $gte: greater then or equals
  • $lt: less then
  • $lte: less then or equals
  • $in, $nin
  • 논리 연산자: $or, $and, $not, $nor
  • regex 연산자
  • where 연산자
  • slice 연산자
  • elemMatch 연산자
profile
junior backend-developer 👶💻

0개의 댓글