본문 바로가기

프로젝트형 IoT 서비스 개발 4회차/3. 게이트웨이 디바이스 제어

[Day48] 2022-04-06(수) MongoDB3 - CRUD2(QUERY, DELETE) - 김서연 강사님

728x90

[1] CRUD Operations

  1. QUERY

    - db.컬렉션명.find(조건, 조회할 필드)

    - db.컬렉션명.find(조건, 조회할 필드).pretty( ) => 보기 좋게 정렬하여 조회

 

    - 조건(query) : 조건에 대한 정보를 JSON 형식으로 표기 ex) {id: "abcd"}

      - 조건을 사용하는 방식은 UPDATE에서도 동일하게 사용 가능

      - 조건을 위한 Query Selector들은 2.에서 별도로 공부

    - 조회할 필드(projection) : {조회할 필드명: 1} 과 같이 표기    ex) {name: 1, addr: 1}

    1) 모든 document의 모든 필드 조회

      - db.컬렉션명.find( ) 혹은 db.컬렉션명.find({ })

      - SQL : SELECT * FROM 테이블명

    2) 모든 document의 특정 필드 조회

      - db.컬렉션명.find({ }, 조회할 필드)

      - SQL : SELECT 필드명1, 필드명2,... FROM 테이블명

      - 조건에 빈 객체( { } )를 넣어주어야 한다.

      ex) db.score.find({ }, {id:1, name:1})

    3) 조건에 맞는 document의 모든 필드 조회

      - db.컬렉션명.find(조건)

      - SQL : SELECT * FROM 테이블명 WHERE 조건

      - 조회할 필드를 생략하면 된다.

    4) 조건에 맞는 document의 특정 필드 조회

      - db.컬렉션명.find(조건, 조회할 필드)

      - SQL : SELECT 필드명1, 필드명2,... FROM 테이블명 WHERE 조건

 

  2. QUERY Selectors

https://www.mongodb.com/docs/v3.6/reference/operator/query/

 

Query and Projection Operators — MongoDB Manual

Navigation This version of the documentation is archived and no longer supported. Reference > Operators > Query and Projection Operators Query and Projection Operators Note For details on specific operator, including syntax and examples, click on the speci

www.mongodb.com

    1) 비교 (Comparison)

      - $eq : equal, 주어진 조건의 값과 일치 (==)

        ex1) db.score.find( { java: 88 } )

        ex2) db.score.find({ java: { $eq: 88 } } )

      - $ne : not equal, 일치X (!=)

        ex) db.score.find( { java: { $eq: 88 } } )

 

      - $gt : greater than, 크다 (>)

        ex) db.score.find( { java: { $gt: 88 } } )

      - $gte : greater than or equal, 크거나 같다 (>=)

        ex) db.score.find( {java: { $gte: 88 } } )

      - $lt : less than, 작다 (<)

        ex) db.score.find({ java: { $lt: 88 } } )

      - $lte : less than or equal, 작거나 같다 (<=)

        ex) db.score.find({ java: { $lte: 88 } } )

 

      - 90<=java<=100 : 콤마( , ) 로 구분하거나, 논리 연산자 and 사용

        ex) db.score.find( { java: { $gte: 90, $lte: 100 } } )

        ex) db.score.find( { $and: [ { java: { $gte: 90 } }, { java: { $lte: 100 } } ] } )

      - java>=90 or jave<=80 : 논리 연산자 or 사용

        ex) db.score.find( { $or: [ { java: { $gte: 90 } }, { java: { $lte: 80 } } ] } )

        ex) db.score.find( { java: { $or: [ { $gte: 90 }, { $lte: 80 } ] } } )  => 틀린 방식

 

      - $in : 여러 값들(배열) 중 하나라도 일치

        ex) db.score.find({ java: { $in: [ 97, 98 ] } } )

      - $nin : 여러 값들(배열) 중 어느 하나도 일치X

        ex) db.score.find({ java: { $nin: [ 97, 98 ] } } )

 

    2) 논리 (Logical)

      - 두 개 이상의 필드에서 조건을 적용 - not 제외

      - 조건은 배열로 정의 ( 즉, 필드명이 없는 단순 배열은 사용 못함 ) - not 제외

 

      - $and : 두 개 이상의 조건이 모두 true -> true

        ex) db.score.find( { $and: [ { dept: "총무" }, { addr: "인천" } ] } )

      - $or : 두 개 이상의 조건 중 하나라도 true -> true

        ex) db.score.find( { $or: [ { dept: "총무" }, { addr: "인천" } ] } )

      - $nor : 모든 조건을 만족하지 않는 document와 조건 판단할 필드가 없는 document까지 모두 조회

        ex) db.score.find( { $nor: [ { dept: "총무" }, { addr: "인천" } ] } )

 

      - $not : 조건을 만족하지 않는 document와 조건 판단할 필드가 없는 document까지 모두 조회(단일 필드)

        ex) db.score.find( { java: { $not: { $lte: 90 } } } )

        ex) db.score.find( { java: { $not: { $gte: 90, $lte: 100 } } } )

[비교, 논리 연산자 연습]

1. id가 song, kang, hong 인 데이터를 조회
 1) or 사용
  db.score.find( { $or : [ { id: "song" }, { id: "kang" }, { id: "hong" } ] } )
  틀린 방식 -> db.score.find( { id : {$or : [ "song", "kang", "hong" ] } } )
  
 2) in 사용
  db.score.find( { id : { $in: [ "song", "kang", "hong" ] } } )

2. id가 song, kang, hong 이 아닌 데이터를 조회
 1) nor 사용
  db.score.find( { $nor : [ { id: "song" }, { id: "kang" }, { id: "hong" } ] } )
  
 2) nin 사용
  db.score.find( { id : { $nin: [ "song", "kang", "hong" ] } } )

 

  3. Null 필드 조건

    - db.score.insert( { id: "python", name: "파이썬", java: null } ) 로 insert 후 테스트

    - 두 가지 방식으로 조회 가능

    1) db.score.find({필드명:null})

      - 해당 필드가 없는 document뿐만 아니라, 해당 필드가 있지만 값이 null인 document까지 조회

      ex) db.score.find({jave:null}=> 위에서 insert 했던, id가 "python"인 document까지 조회

    2) db.score.find({필드명: {$exists: false}})

      - 해당 필드가 없는 document만 조회

      ex) db.score.find({java: {$exists: false}}) => 위에서 insert 했던, id가 "python"인 document 제외하고 조회

 

  4. 조건으로 JavaScript 명령어 사용

    - { $where: "자바스크립트명령" }

      ex) db.score.find( { $where: "this.java > 90" } )

 

  5. Cusor Method

https://www.mongodb.com/docs/v3.6/reference/method/js-cursor/

 

Cursor Methods — MongoDB Manual

Navigation This version of the documentation is archived and no longer supported. Cursor Methods These methods modify the way that the underlying query is executed. Note For details on specific methods, including syntax and examples, click on the specific

www.mongodb.com

    - count( ) : document의 수를 반환

      ex) db.score.find( ).count( )

    - distinct("필드명") : 해당 필드의 값들의 중복을 제외한 값들을 배열로 리턴

      ex) db.getCollection("score").distinct("addr")
          결과 : [ "서울", "안양", "인천", "대구", "제주" ]

      ex) db.getCollection("score").distinct("addr").length

          결과 : 5

 

    - sort( { 필드명: 옵션값 } ) : 필드값에 대해 정렬 (옵션:  1=오름차순,  -1=내림차순)

    - limit(숫자) : 매개변수 숫자 갯수의 document를 조회

      ex) db.score.find({}, {id:1, name:1, java:1, servlet:1}).sort({java:-1}).limit(5)

    - skip(숫자) : 매개변수 숫자 갯수의 document를 제외하고 document 조회

      ex) db.score.find({}, {id:1, name:1, java:1, servlet:1}).skip(3)

 

    - hasNext( ) : 커서에 document가 있으면 true 반환

    - next( ) : 커서에서 다음 document를 반환

// JavaScript 사용 예

var alldata = db.score.find()
var size = db.score.find().count()
// cursor 안에 저장된 document의 갯수만큼 반복해서 작업하겠다는 의미
while(alldata.hasNext()){
	var one = alldata.next()    // cursor에서 document 하나를 꺼내어 반환
	one.num = 10000          // 꺼낸 document에 num필드를 추가하고 10000으로 값을 저장
	db.score.save(one)          // 작업한 one에 저장된 document를 score 컬렉션에 save
}

    ※ db.collection.save(document)

      - 동일한 _id의 document가 있으면 update, 없으면 insert를 수행(Collection method)

https://www.mongodb.com/docs/v3.6/tutorial/iterate-a-cursor/

 

Iterate a Cursor in the mongo Shell — MongoDB Manual

Navigation This version of the documentation is archived and no longer supported. Iterate a Cursor in the mongo Shell The db.collection.find() method returns a cursor. To access the documents, you need to iterate the cursor. However, in the mongo shell, if

www.mongodb.com

 

  6. 정규표현식(Regular Expression)

    - 문자열에서 패턴과 일치하는 문자가 있는지 찾을 수 있도록 지원

    - 문자, 기호를 이용해서 특정 문자를 찾는다.

    - 문자나 기호는 내부적으로 의미를 갖고 있다.

    - 거의 대부분의 언어에서 동일하게 작업

    - $regex 연산자 이용하거나 find 메소드에서 사용할 수 있다.

    

    - ^ : 문자열의 시작

    - $ : 문자열의 종료

    - . : 임의의 한 글자 의미(한글, 영문 상관 없음)

    - | : or 의 의미

    - i : 대소문자 구분 없이 조회

      ex) db.score.find( { id: /a|P/i } )  => id에 대소문자 구분 없이 a또는 p가 들어간 document 조회

    - /값/ : RDBMS의 like 연산과 동일 => where addr like %값%

    - A-Z : 영문자 대문자

    - a-z : 영문자 소문자

    - 0-9 : 숫자

    - 가-힣 : 한글

    - [ ] : 문자의 집합이나 범위를 나타냄

      ex1) [a-z] => 소문자 a에서 소문자 z사이의 모든 문자

      ex2) [^a-f] => 여기서 ^는 not의 의미로 a에서 f를 제외한 문자(e~z, A~Z, 한글, 영문, 특수문자 등)를 의미

    - { } : 횟수나 범위 체크

      ex1) k{5} => k가 5번 반복

      ex2) a{3,5} => a가 3~5번 반복

    

    - 이 외에도 많은 문자와 기호가 있다.

 

  7. DELETE

    - db.컬렉션명.remove(조건)

    - update와 remove는 find( )에서 적용한 조건을 동일하게 사용할 수 있다.

 

[2] Query 연습 예제

1. exam collection에서 이름과 주소와 servlet점수를 출력해보자

	db.exam.find( {}, {name: 1, addr: 1, servlet: 1})

2. exam collection에서 java점수 중 70점 이상을 출력해보자

	db.exam.find( { java: { $gte: 70 } } )

3. exam collection에서 이름, java점수를 출력하고 bonus가 2000이상인 사람만 출력해보자

	db.exam.find( { bonus: { $gte: 2000 } }, { name: 1, java: 1 } )

4. exam에서 dept가 인사이면서 addr이 안양이거나 대구인 document 출력

	db.exam.find( { $and: [ { dept: "인사" }, { addr: { $in: [ "안양", "대구" ] } } ] } )

5. exam이 servlet점수가 70에서 90사이이며 dept가 총무인 document 조회

	db.exam.find( { $and: [ { servlet: { $gte: 70, $lte: 90 } }, { dept: "총무" } ] } )

6. exam에서 이름에 김씨인 사람 조회해보기

	db.exam.find( { name: /^김/ } )

7. exam에서 servlet점수가 가장 낮은 document와 가장 높은 document 출력

	db. exam.find( ).sort( { servlet: 1 } ).limit(1)
	db. exam.find( ).sort( { servlet: -1 } ).limit(1)

8. java점수가 가장 높은 document중에 7개를 출력하되 2개를 건너뛰고 출력

	db. exam.find( ).sort( { servlet: -1 } ).skip(2).limit(7)

9. 아이디에 n과 o가 들어가는 document 구하기

	db.exam.find( { id: /n|o/ } )

 

- 끝 -

728x90