简体   繁体   中英

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 ?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM