本文介绍了在Mongo中,我如何只显示共享密钥最高价值的文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在名为商店"的集合中有以下四个文档:

Say I have the following four documents in a collection called "Store":

{ item: 'chair', modelNum: 1154, votes: 75 }
{ item: 'chair', modelNum: 1152, votes: 16 }
{ item: 'table', modelNum: 1017, votes: 24 }
{ item: 'table', modelNum: 1097, votes: 52 }

我只想查找每种项目类型中票数最高的文档.这个简单示例的结果将返回modelNum:1154和modelNum:1097.根据客户输入的投票评分,向我展示最受欢迎的椅子和桌子模型.

I would like to find only the documents with the highest number of votes for each item type.The result of this simple example would return modelNum: 1154 and modelNum: 1097. Showing me the most popular model of chair and table, based on the customer inputed vote score.

编写此查询并按投票降序对其进行排序的最佳方法是什么?我正在使用流星进行开发,但我认为这不会产生影响.

What is the best way write this query and sort them by vote in descending order? I'm developing using meteor, but I don't think that should have an impact.

Store.find({????}).sort({votes: -1});

推荐答案

如果您希望在Meteor上和客户端上执行此操作,则只需使用each循环和基本查找. Minimongo将数据保留在内存中,因此我认为额外的find调用并不昂贵.

If you are looking to do this in Meteor and on the client I would just use an each loop and basic find. Minimongo keeps the data in memory so I don't think additional find calls are expensive.

像这样:

 Template.itemsList.helpers({
   items: function(){
     var itemNames = Store.find({}, {fields: {item: 1}}).map( 
       function( item ) { return item.item; }
     );
     var itemsMostVotes = _.uniq( itemNames ).map( 
       function( item ) {
         return Store.findOne({item: item}, {sort: {votes: -1}});
       }
     );
     return itemsMostVotes;
   }
 });

我已切换到findOne,因此它返回对象数组而不是像find那样的游标.如果您确实想要光标,则可以使用itemMostVotes中的_ids查询minimongo.

I have switched to findOne so this returns an array of objects rather than a cursor as find would. If you really want the cursor then you could query minimongo with the _ids from itemMostVotes.

您还可以使用下划线groupBy和sortBy 功能来做到这一点.

You could also use the underscore groupBy and sortBy functions to do this.

这篇关于在Mongo中,我如何只显示共享密钥最高价值的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 03:33