Database Reference
In-Depth Information
■
You can use the following shortcut in the
find()
function to skip and limit your
results:
find ( {}, {}, 10, 20 )
. here, you limit the results to 10 and skip the
first 20 documents.
Note
Working with Capped Collections, Natural Order, and
$natural
There are some additional concepts and features you should be aware of when sorting
queries with MongoDB, including capped collections, natural order, and
$natural
. We'll
explain what all of these terms mean and how you can leverage them in your sorts in
this section.
The
natural order
is the database's native ordering method for objects within a
(normal) collection. So, when you query for items in a collection, the items are returned
by default in the
forward natural order
. This is usually identical to the order in which
items were inserted; however, that is not guaranteed to be the case, as data can move
when it no longer fits on its old location after being modified.
A
capped collection
is a collection in your database where the natural order is
guaranteed to be the order in which the documents were inserted. Guaranteeing that the
natural order will always match the insertion order can be particularly useful when you're
querying data and need to be absolutely certain that the results returned are already
sorted based on their order of insertion.
Capped collections have another great benefit: they are a fixed size. Once a capped
collection is full, the oldest data will be purged, and newer data will be added at the end,
ensuring that the natural order follows the order in which the records were inserted. This
type of collection can be used for logging and auto-archiving data.
Unlike a standard collection, a capped collection must be created explicitly, using
the
createCollection
function. You must also supply parameters that specify the size
(in bytes) of the collection you want to add. For example, imagine you want to create a
capped collection named
audit
with a maximum size of 20480 bytes:
> db.createCollection("audit", {capped:true, size:20480})
{ "ok" : 1 }
Given that a capped collection guarantees that the natural order matches the
insertion order, you don't need to include any special parameters or any other special
commands or functions when querying the data either, except of course when you
want to reverse the default results. This is where the
$natural
parameter comes in. For
example, assume you want to find the ten
most recent
entries from your capped collection
that lists failed login attempts. You could use the
$natural
parameter to find this
information:
> db.audit.find().sort( { $natural: -1 } ).limit ( 10 )