我使用的是nodejs
与猫鼬图书馆为我的MongoDB的互动。
我正在建立一个登陆页面查询(想想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-操场
另外,您也可以使用以下方法实现此目的$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-操场
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句