我有这个产品集合,我想根据自定义排序函数显示 top 10 产品
[{ _id: 1, title, tags:['a'], createdAt:ISODate("2016-01-28T00:00:00Z") } ,
{ _id: 2, title, tags:['d','a','e'], createdAt:ISODate("2016-01-24T00:00:00Z") }]
我想做的是根据可以计算的“魔术分数”对其进行排序。例如,根据这个公式:tag_count*5 - number_of_days_since_it_was_created
。
如果第一个是 1 天大,则得分:
[{_id:1 , score: 4}, {_id:2, score: 10}]
我对如何实现这一点有一些想法,但我不确定它们有多好,尤其是因为我对 mongo 和 meteor 都是新手:
启动一个观察者(Meteor.observe),每次有一个文档 修改(或创建新的),重新计算分数并更新它 关于收藏本身。如果我这样做,我可以使用 $orderBy 我需要它。
经过一番阅读,我发现 mongo 聚合或 map_reduce 可以帮助我达到同样的效果,但据我所知, meteor 不直接支持
将客户端的集合排序为一个数组,但是使用这个 方法我不确定它会如何处理分页(考虑到我订阅的文档数量有限)
感谢您提供任何可以与我分享的信息!
最佳答案
文字函数排序is just being implemented in meteor ,所以你应该能够做类似的事情
Products.find({}, {sort: scoreComparator});
在即将发布的版本中。
您可以使用 transform property when creating collection .在此转换中,将魔术操作存储为函数。
score=function(){
// return some score
};
transformer=function(product){
product.score=score;
// one could also use prototypal inheritance
};
Products=new Meteor.Collection('products',{transform:transformer});
不幸的是,you cannot yet use the sort operator on virtual fields ,因为 minimongo 不支持它。
因此,正如您提到的,在 minimongo 中既不支持虚拟字段排序也不支持文字函数排序的最终后备是客户端排序:
// Later, within some template
scoreComparator=function(prd1,prd2){
return prd1.score()-prd2.score();
}
Template.myTemplate.helpers({
products:function(){
return Products.find().fetch().sort(scoreComparator);
}
});
i'm not sure how it will behave with pagination (considering that i subscribe to a limited number of documents)
EDIT :确实会在订阅的文档中计算分数。
关于mongodb - meteor 中mongodb集合的自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35141284/