오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-04 00:00
관리 메뉴

우노

[MongoDB] Aggregation 본문

Database/MongoDB

[MongoDB] Aggregation

운호(Noah) 2020. 7. 3. 12:48

Aggregation이란?

  • Aggregation은 파이프라인으로 구성된다.

    • Project : 한 번 걸러서 다음 operation으로 넘긴다.
    • Match : 조건에 맞는 애들만 필터링한다.
    • Limit, Skip : 제한
    • Group : 그룹화
    • Sort : 정렬
  • Aggregation은 각각의 operation들이 , 로 구분 돼 리스트형식으로 들어간다.

      db.products.aggregate([
          {$match: ...}, 
          {$group: ...}, 
          {$sort: ...}
      ])
    

Match

  • filtering을 뜻한다.

  • { $match: { } }

      // aggregate의 match는 find와 동일한 결과!
      db.zipcodes.aggregate( 
          [ {$match: {city: "GOSHEN"} } ] 
      )
    
      db.zipcodes.find( { city: "GOSHEN" } )
    
  • regex

    • A로 시작하는 city를 다 보여준다.

        db.zipcodes.aggregate( [
            {$match: { city: { $regex: "^A" } } }
        ])
      
    • 부호가 들어간 애들을 다 보여준다.

        db.zipcodes.aggregate( [
        {$match: { city: { $regex: ".*GO.*" } } }
        ])
      

Count

  • { $count: }

    • count한 결과값을 cities라는 값에 저장한다!

        db.zipcodes.aggregate( 
            [ {$match: {city: "GOSHEN"} }, 
                {$count: "cities"} ] 
        )
      

Project

  • 어떤 필드를 쓸건지에 대한 언급!

    • { $project: { <specification(s)> } }

        db.zipcodes.aggregate( [
            {$match: {city: "GOSHEN"} }, 
            {$project: { _id: 0, city: 1, pop: 1 } } 
        ] )
      

Limit

  • 개수 제한

    • { $limit: }

        db.zipcodes.aggregate( [
            {$match: {city: "GOSHEN"} },
            {$limit: 5},
            {$project: { _id: 0, city: 1, pop: 1 } } ] 
        )
      

Sort

  • { $sort: { : , : ... } }

      db.zipcodes.aggregate( [
          {$match: {city: "GOSHEN"} },
          {$sort: {pop: 1} },
          {$limit: 5},
          {$project: {_id: 0, city: 1, pop: 1 } } ] 
      )

gte

  • $and, $equal, $gt, $lt, $ne, $not 등 존재

    • {$gte: [ , ] }

    • popGte라는 필드를 만드는데, pop이 100보다 큰 애들만 뽑아준다!

        db.zipcodes.aggregate( [
            {$match: {city: "GOSHEN"} }, 
            {$project: {_id: 0, city: 1, pop: 1, 
            popGte: { $gte: [ "$pop", 1000 ] } } }
        ])
      

Group

  • { $group: { _id: , : { : }, ... } }

  • Group with first

    • state 필드 기준으로 그룹화한다.

    • 가장 먼저 나오는 element의 city값을 가져와서 biggestPopCity에 넣어준다.

        db.zipcodes.aggregate( [
        { $sort: { state: 1, pop: -1 } },
        { $group: { _id: "$state", biggestPopCity: { $first: "$city"}, biggestPopState: { $first: "$pop" } } },
        { $sort: { _id: 1 } } 
        ] )
      
  • Group with last

      db.zipcodes.aggregate( [
          { $sort: { state: 1, pop: -1 } },
          { $group: { _id: "$state", smallestPopCity: { $last: "$city"}, smallestPopState: { $last: "$pop" } } }, 
          { $sort: { _id: 1 } } 
      ] )
    
  • Group with sum

      db.zipcodes.aggregate( [
          { $group: { _id: "$state", totalPop: { $sum: "$pop" } } }, 
          { $match: { totalPop: { $gt: 10*1000*1000 } } } 
      ] )
    
  • Group with min, max

      db.zipcodes.aggregate([
      { $group:{ _id:"$state", maxPop:{$max:"$pop"}, minPop:{$min:"$pop"} } }
      ])
    
  • push

    • 값들을 모아 리스트를 만드는 것!

    • 값의 중복이 허용된다!

    • { $push: }

        db.zipcodes.aggregate([
            {$group:{_id:"$state", city_list:{$push:"$city"}}},
            {$match:{_id:"AZ"}}
        ])
      
  • 마지막에 ciry_list의 길이를 numberOfCityNames로 나타낸다!

      db.zipcodes.aggregate([
          {$group:{_id:"$state", city_list:{$push:"$city"}}}, 
          {$match:{_id:"CA"}},
          {$project: {numberOfCityNames: { $size: "$city_list" }}}
      ])
    
  • addToSet

    • 값들을 모아 Set을 만드는 것!

    • 값의 중복 허용이 안된다!

    • { $addToSet: }

        db.zipcodes.aggregate([
            {$group:{_id:"$state", city_list:{$addToSet:"$city"}}},
            {$match:{_id:"AZ"}}
        ])
      
  • 마지막에 ciry_list의 길이를 numberOfCityNames로 나타낸다!

      db.zipcodes.aggregate([
          {$group:{_id:"$state", city_list:{$addToSet:"$city"}}}, 
          {$match:{_id:"CA"}},
          {$project: {numberOfCityNames: { $size: "$city_list" }}} 
      ])
    

out

  • 또 다른 컬렉션으로 넣어주는 것!

  • { $out: ‘’ }

      db.zipcodes.aggregate( [ 
          {$match: {city: "GOSHEN"}}, 
          {$project:{_id:0, city:1, pop:1}}, 
          {$out: 'goshen_pop'} 
      ] )
    
      db.goshen_pop.find()
    

'Database > MongoDB' 카테고리의 다른 글

[MongoDB] Projection  (0) 2020.07.03
[MongoDB] Cursor  (0) 2020.07.03
[MongoDB] mongoimport  (0) 2020.07.03
[MongoDB] Index  (0) 2020.07.02
[MongoDB] Delete Collection  (0) 2020.07.02
Comments