簡體   English   中英

在Mongo中,我如何只顯示共享密鑰最高價值的文檔?

[英]In Mongo, how do I only display documents with the highest value for a key that they share?

假設我在一個名為“商店”的集合中有以下四個文檔:

{ 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。根據客戶輸入的投票評分,向我展示了最受歡迎的椅子和桌子模型。

編寫此查詢並按降序對它們進行排序的最佳方式是什么? 我正在使用流星進行開發,但是我認為這不會產生影響。

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

您可以使用$first$last聚合運算符來實現所需的功能。 僅當$group跟隨$sort時,這些運算符才有用。 使用$first的示例:

db.collection.aggregate([
    // Sort by "item" ASC, "votes" DESC
    {"$sort" : {item : 1, votes : -1}}, 
    // Group by "item" and pick the first "modelNum" (which will have the highest votes)
    {"$group" : {_id : "$item", modelNum : {"$first" : "$modelNum"}}}
])

這是輸出:

{
        "result" : [
                {
                        "_id" : "table",
                        "modelNum" : 1097
                },
                {
                        "_id" : "chair",
                        "modelNum" : 1154
                }
        ],
        "ok" : 1
}

如果您希望在Meteor和客戶端上執行此操作,則只需使用each循環和基本查找。 Minimongo將數據保留在內存中,因此我認為額外的find調用並不昂貴。

像這樣:

 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。

您還可以使用下划線groupBy和sortBy函數來執行此操作。

您將需要使用聚合框架。

所以

db.Store.aggregate(
    {$group:{_id:"$item", "maxVotes": {$max:"$votes"}}}
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM