티스토리 뷰

MongoDB를 처음 사용해 보는데요, JSON 문서처럼 데이터를 저장할 수 있다는 게 굉장히 매력적이라고 생각해요.

 

스키마가 없는 데이터베이스로, JSON 형식 데이터를 다룬다. 몽고DB가 자동으로 각 데이터의 고유 ID를 부여한다.
collection은 RDBMS의 테이블과 비슷한 개념이다. nested data structure를 저장할 수 있다.

 

아래 유튜브 영상과 몽고DB 도큐먼트를 참고하여 작성하였습니다 :)

https://www.youtube.com/watch?v=ofme2o29ngU&t=1182s 

참고 영상

https://docs.mongodb.com/manual/crud/

 

MongoDB CRUD Operations — MongoDB Manual

Docs Home → MongoDB ManualCRUD operations create, read, update, and delete documents.Create or insert operations add new documents to a collection. If the collection does not currently exist, insert operations will create the collection.MongoDB provides

docs.mongodb.com


1. 존재하는 모든 DB 확인

show dbs
  • 막 생성한 DB에 데이터가 없다면, show dbs 명령어 결과로 해당 DB가 출력되지 않는 듯합니다.

 

 

2. DB 생성

use [new DB name]
  • 기존에 없던 DB명을 입력하면 새로운 DB가 자동으로 생성됩니다.
  • 출력 메시지: switched to db [new DB name]

 

 

3. 데이터 삽입

db.collection.insertOne({ ex1: 'example one', ex2: 'example2' })
db.collection.insertMany( [ { obj1: "object one"}, {obj2: "object 2"} ] )
  • 해당 테이블명을 가진 테이블로 데이터가 추가됩니다.
  • insertOne() - 데이터 오브젝트 1개를 입력한다는 의미입니다.
  • isnertMay() - 데이터 오브젝트 1개 이상을 입력한다는 의미입니다.
  • 출력 메시지: (1) "insertedId" (2) "insertedIds": [ ]

db.[테이블명].insertOne()의 출력 메시지
db.[테이블명].insertMany() 사용 및 출력 메시지

 

db.collection.insertOne({
    name: "hong gildong",
    age: 17,
    scores: {
    	english: 80,
        math: 80,
        korean: 80,
        history: 80
    },
    hobbies: ["running", "reading", "watching movies"]
})
  • scores - nested data structure 입력이 가능합니다.
  • hobbies - value 값에 리스트가 올 수 있습니다.

 

 

4. 데이터 읽기

    (a) 기본 읽기

db.collection.find()
db.collection.find().limit(n)
db.collection.find().sort({key1: 1, key2: -1})
db.collection.find().skip(n)
  • find() - 모든 데이터가 JSON 형식으로 출력됩니다.
  • limit(n) - 전체 데이터 중 n개만 출력됩니다.
  • sort( { key: 1/-1 } )
    • 정렬 기준: key
    • 1 : 오름차순, 알파벳 순서
    • -1 : 내림차순, 리버스 알파벳 순서
  • skip(n) : 출력되는 데이터 중 맨 앞 n개의 오브젝트를 제외한 데이터를 출력합니다.

 

    (b) 선택적 읽기

db.collection.find({ key: value })
db.collection.find({ key: value}, { key: 1, key2: 1})
  • find( { key: value } ) - 해당 key의 값이 value와 일치하는 데이터만 출력합니다.
  • find( { key: value }, { key: 1, key2: 1} ) - key: value로 조건에 맞는 데이터 오브젝트에서 key와 key2 컬럼만 출력합니다.
    • 1 : 해당 컬럼을 출력하라는 의미입니다.
    • 0 : 해당 컬럼을 출력하지 말라는 의미입니다.
    • key: value 같은 검색 조건없이 특정 컬럼만 출력하겠다고, {key:1, key2: 1} 하면 아무런 결과가 반환이 안 되는 듯합니다.

 

db.collection.find({ key: { $eq: value } })
db.collection.find({ key: { $ne: value } })
  • key: { $eq: value } - 전체 데이터 중 key 값이 value와 동일한 (equal) 데이터만 출력합니다.
  • key: { $ne: value } - 전체 데이터 중 key 값이 value와 다른 (not equal) 데이터만 출력합니다.
  • $gt: value - greater than
  • $gte: value - greater than or equal
  • $lt: value - less than
  • $lte: value - less than or equal

 

db.collection.find({ key: { $in: [value1, value2] } })
  • $in - 전체 데이터 중 key 값으로 해당 리스트 내 원소 값을 가진 데이터를 출력합니다.
  • $nin - 전체 데이터 중 key 값으로 해당 리스트 내 원소 값을 가진 데이터는 제외하고 출력합니다.

 

db.collection.find({ key: { $exists: true/false } })
  • $exists
    • true : 해당 key를 가진 데이터만 출력합니다. ** key 값이 null이라도 key를 가지고 있다면 함께 출력됩니다.
    • false : 해당 key를 가지 않은 데이터만 출력합니다.

 

db.collection.find({ $and/or : [{ key: value}, {key2: value2}] })
  • $and - 서로 다른 key의 출력 조건을 and로 묶습니다.
    • ex) key 값이 value 이고, key2 값이 value2인 데이터만 출력합니다.
  • $or - 서로 다른 key의 출력 조건을 or로 묶습니다.
    • ex) key 값이 value 이거나, key2 값이 value2인 데이터만 출력합니다.
728x90