Database Reference
In-Depth Information
After you add an item and get its ID back, you can use this information to link the item to another document in
another collection:
>>> laptop = {
... "Type" : "Laptop",
... "Status" : "In use",
... "ItemNumber" : "12345ABC",
... "Tags" : ["Warranty","In use","Laptop"],
... "Owner" : jan[ "_id" ]
... }
>>> items = db.items
>>> items.insert(laptop)
ObjectId('4c5e6f6b4abffe0f34000003')
Now assume you want to find out the owner's information. In this case, all you have to do is query for the
ObjectId
given in the
Owner
field; obviously, this is possible only if you know which collection the data is stored in.
But assume that you don't know where this information is stored. It was for handling precisely such scenarios
that the
DBRef()
function was created. You can use this function even when you do not know which collection holds
the original data, so you don't have to worry so much about the collection names when searching for the information.
The
DBRef()
function takes three arguments; it can take a fourth argument that you can use to specify additional
keyword arguments. Here's a list of the three main arguments and what they let you do:
•
collection
(mandatory)
: Specifies the collection the original data resides in (for example,
people
).
id
(mandatory)
: Specifies the
_id
value of the document that should be referred to.
•
database
(optional)
: Specifies the name of the database to reference.
The
DBRef
module must be loaded before you can use the
DBRef
function, so let's load the module before going
any further:
•
>>> from bson.dbref import DBRef
At this point, you're ready to look at a practical example of the
DBRef()
function. In the following example, you
insert a person into the
people
collection and add an item to the
items
collection, using
DBRef
to reference the owner:
>>> mike = {
... "First Name" : "Mike",
... "Last Name" : "Wazowski",
... "Display Name" : "Wazowski, Mike",
... "Department" : "Entertainment",
... "Building" : "2B",
... "Floor" : 10,
... "Desk" : 120789,
... "E-Mail" : "mw@monsters.inc"
... }
>>> people.save(mike)
ObjectId('4c5e73714abffe0f34000004')