Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: Find document with highest value

I want to just find one document in a collections with the highest value of a specific property.

Assume that documents have the following structure

{
  _id: 'jswehfkwefkjw',
  price: 10,
  ....
}

How do I select the document with the highest price ?

I found this

transactions.find("id" => x).sort({"sellprice" => -1}).limit(1).first();

But I cannot translate this into Meteor :( What I have now looks like this

Articles.find({}, {sort: {price: -1}}).fetch();

But this doesn't do it. Any suggestions ?

like image 361
Jeanluca Scaljeri Avatar asked Mar 28 '14 11:03

Jeanluca Scaljeri


2 Answers

As in the mongo version you need to provide both sort and limit options if you want to both sort and limit the objects returned. Both are described in the meteor docs on find().

If you want to return a cursor with one item that has the highest price then this should work:

Articles.find({},{limit: 1, sort: {price: -1}});  

If you want the object itself then add fetch() or use findOne(). If you use findOne() then the limit option is redundant.

like image 78
user728291 Avatar answered Nov 07 '22 08:11

user728291


I'm not exactly clear by what you mean in "this doesn't do it".

But I would suggest using findOne instead of fetch, since fetch returns an array and you want a document.

Articles.findOne({}, {sort: {price: -1}});

or

Articles.find({},{limit: 1, sort: {price: -1}});

and then use a fetch and grab the first element using array notation [0] or underscore _.first(array)

like image 20
Andreykul Avatar answered Nov 07 '22 07:11

Andreykul