从MongoDB中获取不同的值

问题描述 投票:0回答:1

我的数据记录如下 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
}

如你所见 标题, 网址作者 可同可异 身份证, 创建投票独一无二.

这是我的 Routeapp.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的记录。最好的方法是什么?正确的使用方法是什么?鲜明 在这里?

仅供参考,这是我的pug布局。

extends layout
    block content
      h1 #{title}
      ul.list-group
        each entry, i in entries
          li.list-group-item
            a(href=entry.url)= entry.title
node.js mongodb pug
1个回答
1
投票

app.get("/", (req, res) => { model.aggregate([{ $group: { _id: "$author", author: { $first: "$author" }, vote: { $max: "$vote" }, url: { $first: "$url" }, title: { $first: "$title" } } },{ $sort:{ vote:-1} },{ $limit: 500 }]).exec((err, result) => { if (err) { throw err } res.send(result) }) })


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"}}}]);`
© www.soinside.com 2019 - 2024. All rights reserved.