본문 바로가기
국비교육

MongoDB 수업 3일차

by Diligejy 2019. 4. 17.

1. 오늘 했던 실수

관리자 권한에 들어가지 않고 mongo라고 입력하면 접속이 되지 않는다.

 

2.

자기가 사용하고 있는 DB의 메모리를 보고 싶을 때는 무엇이라고 입력하면 되는가?

db.stats();

 

3.

질문 - myScore vs Score

 

Collections?

 

4. 연습문제

    1) ID와 가격만 출력해보자

    db.Product.aggregate([{$project : {_id:1, Category:1}}]);

    

    2) 가격만 출력해보자. 

    db.Product.aggregate([{$project : {_id:0, Price:1}}]);

 

    3) 가격과 카테고리를 출력하자. 단 가격별 오름차순으로 출력하자 

    db.Product.aggregate([{$project : {_id:0, Price:1, Category :1}}, {$sort : {Price : 1 }}]);

 

    4) SQL에서 ename as "사원의 이름" => ename "사원의 이름" = new ename();

        $

       이름만 출력하되 별칭을 주자.

 

       db.Product.aggregate([

         {$project :{_id:0, "alias_name" :"$Name"}}

         ]);

 

     5) Name은 목록, Price는 가격, Category는 타입이라는 별칭을 주고 출력하자.

         db.Product.aggregate([
         {$project :{_id:0, 목록 : "$Name", 가격 : "$Price", 타입 : "$Category"}}
          ]);

 

     6) 상품의 목록에는 Name을 가격에는 inc_price라는 별칭을 주고 Price에 100을 더하자.

         $add

         db.Product.aggregate([

         {$project : {_id :0, "Name" : "$Name", "inc_price" : $add : ["$Price", 100]}}

          ]);

 

     7) 카테고리로 그룹화를 한 다음 최대 가격을 출력해보자.

         $max

         db.Product.aggregate([

          {$group : {_id : "$Category", max_price : {$max : "$Price"}}}

         ]);

 

     8) 카테고리로 그룹화를 한 다음 최소 가격을 출력해보자.

         $min

         db.Product.aggregate([

          {$group : {_id : "$Category", min_price : {$min : "$Price"}}}

         ]);

 

     9) 상품 목록을 그룹화하고 가격의 합과 가격의 평균과 목록의 개수를 구하자.

         db.Produt.aggregate([

          {$group : {_id : "$Category", sum : {$sum : "$Price"}, avg : {$avg : "$Price" }, count : {$sum :1} }} ]);

 

     10) $literal

        상품 목록을 그룹화한 다음 개수를 구해보자. 

        db.Product.aggregate([

        {$project : {"Category":1, count : {$literal : 1}}}

         ]);

 

       db.Product.aggregate([

       {$project : {"Category" : 1, count : {$literal : 1}}},

       {$group : {_id:"$Category", count : {$sum : "$count"}}}

        ]);

 

     11) Name에서 bread를 찾아 출력하자.

        db.Product.aggregate([

        {$project : {_id:0, Name : 1}},

        {$match : {Name : "bread"}}

        ]);

 

      12) Category에서 food만 출력해보자.

       db.Product.aggregate([

        {$match : {Category : "food"}}

       ]);

  

      13) Category에서 food의 가격의 최대값, 최소값, 총합, 평균, 개수를 출력하자.

        db.Product.aggregate([

        {$match : {Category : "food"}},

        {$group : {_id : "$Category",  max : {$max : "$Price"},

        min : {$min : "$Price"}, sum : {$sum : "$Price"}, avg : {$avg : "$Price"}, count : {$sum : 1}}}

        ]);

         

5. db.Product.mapReduce( mapFunction , reduceFunction ,  )

         emit (args) : 매개파라미터 인자 key, value ->

        다중행 출력할 때 사용되며 매개 인자로 받은 객체를 단일 행으로 리턴한다.

    1) mapFunction 만든다

      function mymap() {

          emit (this.Category, {Category : this.Category, Count : 1, Amount : this.Price});

          };

     

    2) reduceFunction를 만들어 원하는 집계를 구현한다. 

      mymap()에서 만들어놓은 초기 컬렉션을 key, values로 받아온다.

       this.Category, {Category : this.Category, Count : 1, Amount : this.Price})

     function my_reduce(key, values) {

            var result = {Category : key,

                             Count : 0,

                             Amount : 0}

            values.forEach(function (v){

                result.Count += v.Count;

                result.Amount += v.Amount;

            });            

            return result;

            };

 

    3) 맵리듀스에 매핑한다. mapReduce(초기 파라미터, 집계 결과, 출력형식)

        db.Product.mapReduce(mymap, my_reduce, {out : {replace : "myResult"}});

        db.myResult.find();

        

    

6. 연습문제

    1) db.Score.mapReduce(

           function m_map(){

            emit(this.name, {count : 1})

           },

           function m_res(key, value){

            var mycount = {count : 0};

            value.forEach(function(m){

                mycount.count += m.count;

              });

           return mycount;

           },

          {out : "myres01"});

    

      2) db.Score.mapReduce(
      ...    function m_map(){
      ...    emit(this.test, {count :1})
      ... },
      ... function m_res(key, value){
      ... var mycount = {count : 0};
      ... value.forEach(function(m){
      ...    mycount.count += m.count;
     ... });
     ... return mycount;
     ... },
     ... {query : {my_id: "10"}, out:{inline:1}});

          

    4) Score 컬렉션의 그룹별로 

        

 

7. 연습

    Score컬렉션을 View_Score 컬렉션으로 복사한 후 시작

     db.Score.copyTo("View_Score")

 

    1) Score의 name "aaa"을 홍길동으로 변경하라

     db.Score.update(

      { "name" :  "aaa" },

      { $set : { "name" : "eee"}});

 

    2) Score의 name 중에 b로 시작하고 e로 끝나는 레코드를 전체 출력하라. 단 $in을 사용한다. 

    db.Score.aggreegate( "name" : "{ $in: [ /^b/, [ /^e/ ] ] }")

     12) Category에서 food만 출력해보자.

       db.Product.aggregate([

        {$match : {Category : "food"}}

       ]);

 

      db.Score.aggregate ([

        {$match : {"name" : {$in: [/^b/, /e$/}})

 

    3) Score 국어점수 중 80에서 90 사이의 점수를 모두 출력하라.

     db.Score.find({ "kor" : {"$gte" : 80, "$lte" : 90} });

 

    4) Score 수학 점수 중 80점 이하인 점수를 찾아 100점으로 변경 후 출력

     db.Score.update({ "mat" : {"$lte" : 80}}, {$set: {mat:100}}, true);     

 

    5) 이름 eee를 삭제하라.

      db.Score.remove({name:"eee"})

 

    6) Score의 70점 이하 모든 점수를 삭제하라. 

       db.Score.deleteMany({mat : {$lte:70}});

    7) 수학 필드를 지워라

          db.products.update(

              { $unset: { "mat": ""} } );

 

'국비교육' 카테고리의 다른 글

MongoDB 5일차  (0) 2019.04.19
MongoDB 수업 4일차  (0) 2019.04.18
MongoDB 수업 2일차 - 쿼리  (0) 2019.04.16
MongoDB 수업 1일차 - 개론  (0) 2019.04.15
국비교육 76일차  (0) 2019.03.26

댓글