본 글은 글쓴이가 꺼내보기 위함의 목적이 큰 글입니다 :)
파이프라인 개념(이전 단계의 연산결과를 다음 단계연산에 이용)을 토대로 순서대로 파이프라인을 거쳐 문서를 연산하고 하나의 문서의 형태로 집계함.
aggregate([ pipeline ])
pipeline에서 유용하게 쓰는 option들은 아래와 같다.
사용법
model.aggregate([
{
$lookup:[
"from": join하려고 하는 collection 명,
"localField": join하려고 하는 collection 과 공통으로 이어진 model 의 필드명,
"foreignField": model 과 공통으로 이어진 join하려고 하는 collection의 필드명,
"as": join한 값이 들어갈 필드명
]
}
])
.exec();
사용법
model.aggregate([
{ $match: {
'필드명':조건 ,
... 조건은 find 사용시 조건과 동일함
}},
])
.exec();
추가 ) 빈배열 제외 할때
'필드명' :{$exists: true, $not: {$size: 0}},
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 : { "name": 1, 'created_at': -1}},
{ $skip: opt.perPage * opt.page},
{ $limit: opt.perPage }
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://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