Database Reference
In-Depth Information
a document for which an ItemNumber has the value of 3456TFS , and you don't want to return the document's _ id .
The following query accomplishes that, returning the output as shown:
>>> collection.find_one({"ItemNumber" : "3456TFS"} ,fields={'_id' : False})
{
u'Status': u'In use',
u'Tags': [u'Laptop', u'Development', u'In Use'],
u'ItemNumber': u'3456TFS',
u'Location': {
u'Department': u'Development',
u'Building': u'2B',
u'Floor': 12,
u'Owner': u'Walker, Jan',
u'Desk': 120103
},
u'Type': u'Laptop'
}
Note
Python is case-sensitive. Therefore, true and false are not the same as True and False .
If the search criteria are relatively common for a document, you can also specify additional query operators.
For example, imagine querying for {"Department" : "Development"} , which would return more than one result.
We'll look at such an example momentarily; however, first let's determine how to return multiple documents, rather
than just one. This may be a little different than you suspect.
Finding Multiple Documents
You need to use the find() function to return more than a single document. You've probably used this command in
MongoDB many times by this point in the topic, so you're probably feeling rather comfortable with it. The concept is
the same in Python: you specify the query parameters between the brackets to find the specified information.
Getting the results back to your screen, however, works a little differently. Just as when working with PHP and in the
shell, querying for a set of documents will return a cursor instance to you. Unlike when typing in the shell, however, you
can't simply type in db.items.find() to have all results presented to you. Instead, you need to retrieve all documents
using the cursor. The following example shows how to display all documents from the items collection (note that you
previously defined collection to match the collection's name; the results are left out for the sake of clarity):
>>> for doc in collection.find():
... doc
...
Pay close attention to the indentation before the word doc . If this indentation is not used, then an error message
will be displayed, stating that an expected indented block didn't occur. It's one of Python's strengths that it uses such
an indentation method for block delimiters because this approach keeps the code well ordered. Rest assured, you'll
get used to this Pythonic coding convention relatively quickly. If you do happen to forget about the indentation,
however, you'll see an error message that looks something like this:
File "<stdin>", line 2
doc
^
IndentationError: expected an indented block
 
 
Search WWH ::




Custom Search