2015-06-27 68 views
0

我怎樣才能找到這個字段(排序)和mongodb總投票,我使用流星孟戈。這是我的代碼如何查找排序和總數?

Posts.find({},{limit: 5, sort: {vote: -1,owner:-1}}); 

它不工作

{ 
    "_id":123, 
    "owner":"yuda", 
    "vote":12 
} 
{ 
    "_id":124, 
    "owner":"yuda", 
    "vote":3 
} 
{ 
    "_id":125, 
    "owner":"lucy", 
    "vote":42 
} 

我需要由業主和總投票排序結果:

{ 
    "owner":"lucy", 
    "vote":42 
} 
{ 
    "owner":"yuda", 
    "vote":15 
} 

感謝

回答

2

這將產生正確的結果:

// fetch some posts 
var posts = Posts.find({}, {limit: 5}).fetch(); 

// track the count of votes by owner 
var votesByOwner = {}; 

// determine the count of votes by owner 
_.each(posts, function(post) { 
    if (votesByOwner[post.owner] == null) 
    votesByOwner[post.owner] = 0; 
    votesByOwner[post.owner] += post.vote; 
}); 

// reshape and sort the vote data 
var result = _.chain(votesByOwner) 
    .map(function(votes, owner) {return {owner: owner, votes: votes};}) 
    .sortBy('owner') 
    .value(); 

console.log(result); 

也看到這個相關的問題:"group by" queries on meteor collection

+0

感謝您的幫助,您的代碼可以運行良好 – anggaranc