Database Reference
In-Depth Information
{
u'ItemNumber': u'3456TFS',
u'_id': ObjectId('4c57234c4abffe0e0c000002'),
u'Location': {
u'Owner': u'Walker, Jan'
}
}
Next, let's look at the limit() function in action. In this case, you tell the function to return only the ItemNumber
from the first two items it finds in the collection (note that no search criteria are specified in this example):
>>> for doc in collection.find({}, {"ItemNumber" : "true"}).limit(2):
... doc
...
{u'ItemNumber': u'1234EXD', u'_id': ObjectId('4c57207b4abffe0e0c000000')}
{u'ItemNumber': u'2345FDX', u'_id': ObjectId('4c57234c4abffe0e0c000001')}
You can use the skip() function to skip a few items before returning a set of documents, as in the
following example:
>>> for doc in collection.find({}, {"ItemNumber" : "true"}).skip(2):
... doc
...
{u'ItemNumber': u'3456TFS', u'_id': ObjectId('4c57234c4abffe0e0c000002')}
You can also combine the three functions to select only a certain number of items found, while simultaneously
specifying a specific number of items to skip and sorting them:
>>> for doc in collection.find( {'Status' : 'In use'},
... fields={'ItemNumber' : True, 'Location.Owner' : True}).limit(2).skip(1).sort 'ItemNumber'):
... doc
...
{
u'ItemNumber': u'2345FDX',
u'_id': ObjectId('4c57234c4abffe0e0c000001'),
u'Location': {
u'Owner': u'Smith, Simon'
}
}
{
u'ItemNumber': u'3456TFS',
u'_id': ObjectId('4c57234c4abffe0e0c000002'),
u'Location': {
u'Owner': u'Walker, Jan'
}
}
What you just did—limiting the results returned and skipping a certain number of items—is generally known as
paging . You can accomplish this in a slightly more simplistic way with the $slice operator, which will be covered later
in this chapter.
 
Search WWH ::




Custom Search