MongoDB sort top n records

I would like to be able to grab the ten most recent records in the database and sort them by price with the most expensive first. (Date and price are just examples, this could apply to any two sortable fields.) If I sort by price, I don't get the ten most recent records, so I have to sort by time. However, when I sort by time, the results are ordered by time rather than price. Can I make a request that grabs documents on time and orders them at a price? Or do I need to sort the records after the query has returned them?

+3


source to share


1 answer


If your document has a structure similar to:

 {_id: ObjectId("50a8240b927d5d8b5891743c"),
 price: 12,
 date: new Date("Oct 04, 2012")}

      

On the console, you can run the following query:

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

      

Here you will find all the objects for which the date is Oct 04, 2014 , and orders them in descending order by price.

If you want to reverse the sort order, you can replace the sort query with: "price": 1

EDIT:



Also, if you want to have multiple sort fields, for example, get the most recent one in time with the highest price, you can use the following query:

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

      

EDIT 2:

As with the updated comment, the query should get the top ten newest items and sort them by the price that has the most expensive:

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

      

This is the only way I can think of at the moment. Get the first 10 items sorted by date and after that apply another filter to sort by price.

+2


source







All Articles