Getting distinct value from MongoDB

I have below data records in my MongoDB collection;

{
    "_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
}

As you can see title, url and author could be same but _id, created and vote is always unique.

This is my Route in 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
      });
    }
  });
});

This route is displaying 500 records descending order of vote value. This is displaying both records above that have vote values 1619 and 1230. However what i want to achieve is to display only the biggest vote value for same title, url and author. In this example it should display only the record with vote value 1619. What is the best way to do it? What is the correct way of using distinct in here?

And just for your reference this is my pug layout;

extends layout
    block content
      h1 #{title}
      ul.list-group
        each entry, i in entries
          li.list-group-item
            a(href=entry.url)= entry.title

Hello Senol_Sahin :wave:,

To find the max value for a set of fields, you have to do an aggregation. That is write a db.collection.aggregate method (instead of the find).

Distinct values are arrived at using the $group stage of the aggregation query. You can use the $max aggregation operator to get the biggest vote value for the distinct (grouping) of title, url and author fields.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.