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 ?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With