Database Reference
In-Depth Information
You can also combine the preceding code with another key/value pair, as in this example:
>>> for doc in collection.find({ "Location.Building" : "2B", "$or" : [ { "Location.Department" :
"Storage" },
... { "Location.Owner" : "Anderson, Thomas"} ] } ):
... doc
...
The $or operator basically allows you to conduct two searches simultaneously and combine the resulting output,
even if the individual searches have nothing in common with each other. Also, the $or clauses are executed in parallel,
and each clause may use a different index.
Retrieving Items from an Array with $slice
You can use the $slice operator to retrieve a certain number of items from a given array in your document. This
operator provides functionality similar to the skip() and limit() functions; the difference is that those two functions
work on full documents, whereas the $slice operator works on an array in a single document.
Before looking at an example, let's add a new document that will enable us to take a better look at this operator.
Assume that your company is maniacally obsessed with tracking its chair inventory, tracking chairs wherever they
might go. Naturally, every chair has its own history of desks to which it once belonged. The $slice example operator
is great for tracking that kind of inventory.
Begin by adding the following document:
>>> chair = ({
... "Status" : "Not used",
... "Tags" : ["Chair","Not used","Storage"],
... "ItemNumber" : "6789SID",
... "Location" : {
... "Department" : "Storage",
... "Building" : "2B"
... },
... "PreviousLocation" :
... [ "120100","120101","120102","120103","120104","120105",
... "120106","120107","120108","120109","120110" ]
... })
>>> collection.insert(chair)
ObjectId('4c5973554abffe0e0c000005')
Now assume you want to see all the information available for the chair returned in the preceding example, with
one caveat: you don't want to see all the previous location information, but only the first three desks it belonged to:
>>> collection.find_one({'ItemNumber' : '6789SID'}, {'PreviousLocation' : {'$slice' : 3} })
{
u'Status': u'Not used',
u'PreviousLocation': [u'120100', u'120101', u'120102'] ,
u'Tags': [u'Chair', u'Not used', u'Storage'],
u'ItemNumber': u'6789SID',
u'Location': {
 
Search WWH ::




Custom Search