我的MongoDB
集合中有以下数据记录;
{
"_id": { "8uk4f9653fc4gg04dd7ab3d3"},
"title": "my title",
"url": "https://myurl/entry/1ethd485",
"author": "john",
"created": { "2020-05-20T08:25:47.438Z"},
"vote": 1619
},
{
"_id": { "6fd4fgh53fc4gg04dd7gt56d"},
"title": "my title",
"url": "https://myurl/entry/1ethd485",
"author": "john",
"created": { "2020-05-19T04:12:47.457Z"},
"vote": 1230
}
您可以看到标题, URL 和作者可能相同,但创建了 _id , 和投票是始终唯一。
这是我在Route
中的app.js
;
// Home Route
app.get('/', function(req, res){
Entry.find({}).sort({ "vote" : -1 }).limit(500).exec(function(err, entries){
if(err){
console.log(err);
} else {
res.render('index', {
entries: entries
});
}
});
});
此路由正在显示500条记录的投票值降序。这将显示上面两个具有投票值1619和1230的记录。但是,我要实现的是仅显示相同标题,URL和作者的最大投票值。在此示例中,它应仅显示投票值为1619的记录。最佳方法是什么?在这里使用distinct的正确方法是什么?
仅供参考,这是我的哈巴狗布局;
extends layout
block content
h1 #{title}
ul.list-group
each entry, i in entries
li.list-group-item
a(href=entry.url)= entry.title
答案 0 :(得分:1)
if you have to find out distinct along with maximum value the you can use the following command:
`Entry.aggregate([{$group:{_id:"$author",votevalue:{$max:"$vote"}}}]);`
答案 1 :(得分:1)
all()