Rad*_*dan 6 sorting mongodb meteor
我有这个产品集合,我想显示top 10 products基于自定义排序功能
[{ _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") }]
Run Code Online (Sandbox Code Playgroud)
我想要做的是根据可以计算的"魔术得分"对其进行排序.例如,基于这个公式:tag_count*5 - number_of_days_since_it_was_created.
如果第一个是1天,则得分:
[{_id:1 , score: 4}, {_id:2, score: 10}]
Run Code Online (Sandbox Code Playgroud)
我对如何实现这一点有一些想法,但我不确定它们有多好,特别是因为我对mongo和meteor都是新手:
启动观察者(Meteor.observe)并在每次修改文档(或创建新文档)时,重新计算分数并在集合本身上更新它.如果我这样做,我可以使用$ orderBy我需要它.
经过一番阅读后我发现mongo aggregate或map_reduce可以帮助我达到同样的效果,但据我发现,meteor不直接支持它
在客户端将集合排序为一个数组,但使用这种方法我不知道它将如何与分页行为(考虑到我订阅了有限数量的文档)
感谢您提供的任何信息,我可以与您分享!
文字函数排序刚刚在流星中实现,所以你应该能够做类似的事情
Products.find({}, {sort: scoreComparator});
Run Code Online (Sandbox Code Playgroud)
在即将发布的版本中.
您可以在创建集合时使用transform属性.在此变换中,将魔术操作存储为函数.
score=function(){
// return some score
};
transformer=function(product){
product.score=score;
// one could also use prototypal inheritance
};
Products=new Meteor.Collection('products',{transform:transformer});
Run Code Online (Sandbox Code Playgroud)
不幸的是,你还不能在虚拟字段上使用sort运算符,因为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);
}
});
Run Code Online (Sandbox Code Playgroud)
我不确定它将如何与分页表现(考虑到我订阅了有限数量的文件)
编辑:确实将在订阅的文档中计算得分.