본 글은 글쓴이가 꺼내보기 위함의 목적이 큰 글입니다 :)

aggregation : 집계

파이프라인 개념(이전 단계의 연산결과를 다음 단계연산에 이용)을 토대로 순서대로 파이프라인을 거쳐 문서를 연산하고 하나의 문서의 형태로 집계함.

aggregate([ pipeline ])

pipeline에서 유용하게 쓰는 option들은 아래와 같다.

lookup

  • SQL join과 같은 기능을 함.
  • 공통된 document를 통해 다른 collection 의 데이타를 가져 올 수 있음.

사용법

model.aggregate([
	{
		$lookup:[
			"from": join하려고 하는 collection 명,
      "localField": join하려고 하는 collection 과 공통으로 이어진 model 의 필드명,
      "foreignField": model 과  공통으로 이어진 join하려고 하는 collection의 필드명,
      "as": join한 값이 들어갈 필드명
		]
	}
])
.exec();
  • 기존 model 데이타에 as 로 지정한 필드가 추가되어 join 한 값이 나옴.
  • populate 도 얼핏 join 과 같다고 생각되지만, 엄연히 join이 아님. ⇒ 보여주는 것만 가능 할 뿐. (join 한 값에서 find를 실행하려 했으나 접근이 안됨. 필자는 이 문제로 고생함. )

match

  • aggregate 에서 find 완 같은 기능을 담당함.
  • 조건과 일치하는 것을 반환

사용법

model.aggregate([
	{ $match: {
      '필드명':조건 ,
      ... 조건은 find 사용시 조건과 동일함
  }},
])
.exec();

추가 ) 빈배열 제외 할때

'필드명' :{$exists: true, $not: {$size: 0}},
  • join 하려는 collection 함께 검색하려면 lookup으로 join 한 다음에 match로 한꺼번에 검색
model
.aggregate([
    { $lookup: {
        "from": opt.join.collection,
        "localField": opt.join.field,
        "foreignField": opt.join.foreignField,
        "as": 'result_post'
    }},
    { $match: {
        'country': opt.findOption.country
        $or:[{ 'name': opt.findOption.str},{ 'country': opt.findOption.str }],
        'result_post.review' : opt.findOption.review  // join 하고 나온 데이타 검색 
    }},
])
.exec();
❗ paging 적용시 , 사용되는 옵션 : `$sort`, `$skip`, `$limit`

sort

  • filed 기준 조건에 맞게 정렬
{ $sort : { "name": 1, 'created_at': -1}}, 
  • 1 : 오름차순, -1: 내림차순
  • 필드 복수적용, 단수 적용 다 가능함.

skip / limit

  • skip : 해당 수 만큼 skip 한다.
  • limit : 갯수 끊어서 보여줌.
  • paging은 skip 과 limit를 같이 적용하여 구현함.
{ $skip: opt.perPage * opt.page},
{ $limit: opt.perPage }

count

  • aggregate에서 countDocument와 같은 결과를 보려면, group옵션을 이용하여 묶어준 후, count 옵션을 적용해주면 됨.
model
.aggregate([
    { $group: {
        _id: "$_id", // 묶어주는 기준이 되는 필드, 필드명은 앞에 $를 붙여준다.
        count: {
            $sum: 1
        }
    }},
    { $count: 'count'}
])
.exec();

//// 결과
{count: 카운트 결과 숫자}

참고문헌

https://stackoverflow.com/questions/11303294/querying-after-populate-in-mongoose

https://stackoverflow.com/questions/14789684/find-mongodb-records-where-array-field-is-not-empty

https://www.hides.kr/1035

https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate

https://stackoverflow.com/questions/52502542/count-of-mongodb-aggregation-match-results

https://pro-self-studier.tistory.com/61

https://jaehun2841.github.io/2019/02/24/2019-02-24-mongodb-2/#Aggregation-Pipeline

profile
한 걸음 한 걸음 계속 걷는 자가 일류다

0개의 댓글