Database Reference
In-Depth Information
If you get tired of an entire collection, you can use either the drop() or the drop_collection() function to
remove it. Both functions work the same way (one is just an alias for the other, really); specifically, both expect only
one parameter, the collection's name:
>>> db.items.drop()
Last (and far from least because of its potential destructiveness), the drop_database() function enables you to
delete an entire database. You call this function using the Connection module, as in the following example:
>>> c.drop_database("inventory")
Creating a Link Between Two Documents
Database references (DBRefs) are implemented in PyMongo via the DBRef() function as part of the DBRef module
and can be used to create a link between two documents that reside in different locations. This is a field storage
convention, which can be used for application logic. For example, you might create one collection for all employees
and another collection for all the items—and then use the DBRef() function to create a reference between the
employees and the location of the items, rather than typing them in manually for each item.
MongodB cannot ensure that dBrefs are valid. Caution should therefore be taken when deleting documents
that may be linked by dBrefs.
Note
As you may recall from the previous chapters, you can reference data in either of two ways. First, you can add a
simple reference ( manual referencing ) that uses the _id field from one document to store a reference to it in another.
Second, you can use the DBRef module, which brings a few more options with it than you get with manual referencing.
Let's create a manual reference first. Begin by saving a document. For example, assume you want to save the
information for a person into a specific collection. The following example defines a jan dictionary and saves it into the
people collection to get back an ObjectId :
>>> jan = {
... "First Name" : "Jan",
... "Last Name" : "Walker",
... "Display Name" : "Walker, Jan",
... "Department" : "Development",
... "Building" : "2B",
... "Floor" : 12,
... "Desk" : 120103,
... "E-Mail" : " jw@example.com "
... }
>>> people = db.people
>>> people.insert(jan)
ObjectId('4c5e5f104abffe0f34000002')
 
 
Search WWH ::




Custom Search