Database Reference
In-Depth Information
At this point, nothing interesting has happened. Yes, you added a document, but you did so without adding a
reference to it. However, you do have the ObjectId of the document, so now you can add your next document to the
collection, and then use DBRef() to point the owner field at the value of the previously inserted document. Pay special
attention to the syntax of the DBRef() function; in particular, you should note how the first parameter given is the
name of the collection where your previously specified document resides, while the second parameter is nothing
more than a reference to the _id key in the mike dictionary:
>>> laptop = {
... "Type" : "Laptop",
... "Status" : "In use",
... "ItemNumber" : "2345DEF",
... "Tags" : ["Warranty","In use","Laptop"],
... "Owner" : DBRef('people', mike[ "_id" ])
... }
>>> items.save(laptop)
ObjectId('4c5e740a4abffe0f34000005')
As you probably noticed, this code isn't very different from the code you used to create a manual reference.
However, we recommend that you use DBRefs just in case you need to reference specific information, rather than
embedding it. Adopting this approach also means you don't need to look up the collection's name whenever you
query for the referenced information.
Retrieving the Information
You know how to reference information with DBRef() ; now let's assume that you want to retrieve the previously
referenced information. You can accomplish this using the Python driver's dereference() function. All you need to
do is define the field previously specified that contains the referenced information as an argument, and then press the
Return key.
To demonstrate, let's walk through the process of referencing and retrieving information from one document to
another from start to finish. Let's begin by finding the document that contains the referenced data, and then retrieving
that document for display. The first step is to create a query that finds a random document with the reference
information in it:
>>> items.find_one({"ItemNumber" : "2345DEF"})
{
u'Status': u'In use',
u'Tags': [u'Warranty', u'In use', u'Laptop'],
u'ItemNumber': u'2345DEF',
u'Owner': DBRef(u'people', ObjectId('4c5e73714abffe0f34000004')),
u'_id': ObjectId('4c5e740a4abffe0f34000005'),
u'Type': u'Laptop'
}
Next, you want to store this item under a person dictionary:
>>> person = items.find_one({"ItemNumber" : "2345DEF"})
 
Search WWH ::




Custom Search