MongoDB sort top n entries -


i able grab ten recent entries in database , sort them price expensive first. (date , price examples; apply 2 sortable fields.) if sort price, won't ten recent entries, have sort time. when sort time, though, results ordered time instead of price. can make query grabs documents time , orders them price? or have sort entries after query has returned them?

if document has structure similar to:

 {_id: objectid("50a8240b927d5d8b5891743c"),  price: 12,  date: new date("oct 04, 2012")} 

from console run following query:

db.prices.find({'date':isodate("oct 04, 2012")}).sort({'price':-1}); 

this find objects have date set oct 04, 2014 , orders them descending based on price.

if want reverse sorting order can replace sorting query with: 'price':1

edit:

also if want have multiple sorting fields, getting recent in time highest price use query bellow:

db.prices.find().sort({'price':-1,'date':-1}) 

edit 2:

as updated comment query should top ten newest items , sort them price having expensive first:

db.prices.find().sort({'date':-1}).limit(10).sort({'p':-1}); 

this way can think of @ moment. first 10 items sorted date , after apply filter sort them price.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -