【问题标题】:Getting distinct value from MongoDB从 MongoDB 获得独特的价值
【发布时间】:2020-05-20 19:49:20
【问题描述】:

我的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
}

如您所见,titleurlauthor 可能相同,但 _id 已创建vote总是独一无二的

这是我在app.js中的Route

// 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

【问题讨论】:

    标签: node.js mongodb pug


    【解决方案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) }) })

    【讨论】:

    • 嗯,这似乎带来了结果,但它并没有按投票降序排序。
    • 您也可以按降序排列进行投票。 { $sort:{ vote:-1} } 在你的聚合函数中应用这个对象。
    • 我已经编辑了答案,你可以试试。现在
    • 我已经对答案进行了更改,这肯定会起作用。
    • 我也加了限制,你可以试试
    【解决方案2】:
    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"}}}]);`
    

    【讨论】:

    • 您能否详细说明一下。这如何符合我的 "Entry.find({}).sort({ "vote" : -1 }).limit(500)" 标准。我还是想用它。
    • 你可以使用这个Entry.distinct("author").exec((err,results)) 这个方法的问题是它也会以最小值返回你的对象。但在上面发生的情况是,它会选择同一张支票,选择一个具有最大投票数的不同支票。我认为您想与唯一作者对象一起检索最大投票。
    • 实际上我想要最大投票以及唯一的作者、标题和网址。
    • 此方法将检索带有作者、标题和 url 的整个对象
    • 我已经为您进行了更改并将代码发布在下面,在您的应用程序中尝试它,您将得到结果
    猜你喜欢
    • 2011-03-26
    • 2021-01-21
    • 1970-01-01
    • 2020-01-09
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多