mongoDB 상호 작용을 위해 mongoose 라이브러리nodejs
와 함께 사용 하고 있습니다.
랜딩 페이지 쿼리 (Netflix 페이지 생각)를 만들고 있으며 각 범주 (코미디, 공포, 드라마 등)에 대해 ~ 15 개의 결과를 얻어야합니다.
아래 그림과 같이 각 "카테고리"에 대한 쿼리를 전송하고 콜백 문제와 데이터베이스에 대한 무거운 요청을 처리하는 것은 훌륭한 솔루션이 아닌 것 같습니다.
const categories = ['horror','drama','comedy']
let counterCallback = 0
let allShows = []
categories.map(category =>{
Show.find({category: category},{limit: 15}, (err, shows)=>{
if(shows){ allShows.push(shows)}
allShows++
if(allShows === categories.length){ return res.json(allShows) }
})
})
$or
요청을 할까 생각하고 있었는데 각 "또는"의 수를 제한 할 수는 없습니다.
const categories = ['horror','drama','comedy']
Show.find({
$or:categories.map(category=> {return {category: category} })
},{limit: 10})
"카테고리"당 결과 수를 제한하는 요청을 어떻게받을 수 있습니까?
감사
MongoDB의 집계 프레임 워크 를 활용하여 복잡한 쿼리를 실행할 수 있습니다. 아래 쿼리를 시도해보세요.
var categories = ['horror', 'comedy', 'drama']
Show.aggregate([
/** This $match would help to limit docs to particular categories, as each pipeline in facet stage has to iterate to all docs in collection for thrice as 3 categories given, So at least limiting docs to needed categories. */
{ $match: { category: { $in: categories } } },
{
$facet: {
'horror': [{ $match: { category: 'horror' } }, { $limit: 1 }],
'comedy': [{ $match: { category: 'comedy' } }, { $limit: 1 }],
'drama': [{ $match: { category: 'drama' } }, { $limit: 1 }]
}
}])
테스트 : MongoDB-Playground
또는 다음을 사용하여 얻을 수 $group
있습니다.
Show.aggregate([
{ $match: { category: { $in: categories } } },
{ $group: { _id: '$category', shows: { $push: '$$ROOT' } } },
{ $project: { category: '$_id', _id: 0, shows: { $slice: ['$shows', 1] } } },
/** Below two stages are optional */
{ $group: { _id: '', data: { $push: '$$ROOT' } } },
{ $project: { _id: 0 } }
])
테스트 : MongoDB-Playground
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다