Database Reference
In-Depth Information
Using the Sort, Limit, and Skip Functions
MongoDB includes several functions that you can use for more precise control over your
queries. We'll cover how to use the sort , limit , and skip functions in this section.
You can use the sort function to sort the results returned from a query. You can sort
the results in ascending or descending order using 1 or -1 , respectively. The function
itself is analogous to the ORDER BY statement in SQL, and it uses the key's name and
sorting method as criteria, as in this example:
> db.media.find().sort( { Title: 1 })
This example sorts the results based on the Title key's value in ascending order.
This is the default sorting order when no parameters are specified. You would add
the -1 flag to sort in descending order.
if you specify a key for sorting that does not exist, the values will be returned in
their ascending insertion order.
Note
You can use the limit() function to specify the maximum number of results
returned. This function requires only one parameter: the number of the desired results
returned. When you specify '0, all results will be returned. The following example returns
only the first ten items in your media collection:
> db.media.find().limit( 10 )
Another thing you might want to do is skip the first n documents in a collection. The
following example skips the first twenty documents in your media collection:
> db.media.find().skip( 20 )
As you probably surmised, this command returns all documents within your
collection, except for the first twenty it finds. Remember: it finds documents in the order
they were inserted.
MongoDB wouldn't be particularly powerful if it weren't able to combine these
commands. However, practically any function can be combined and used in conjunction
with any other function. The following example limits the results by skipping a few and
then sorts the results in descending order:
> db.media.find().sort ( { Title : -1 } ).limit ( 10 ).skip ( 20 )
You might use this example if you want to implement paging in your application.
As you might have guessed, this command wouldn't return any results in the media
collection created so far, because the collection contains fewer documents than were
skipped in this example.
 
 
Search WWH ::




Custom Search