Databases Reference
In-Depth Information
user and the “MongoDB is fun!” note, both of which are associated with Kristina's note.
This dereferencing is easy to implement; we use the value of the "$ref" key to get the
collection to query on, and we use the value of the "$id" key to get the "_id" to
query for:
> var note = db.notes.findOne({"_id" : 20});
> note.references.forEach(function(ref) {
... printjson(db[ref.$ref].findOne({"_id" : ref.$id}));
... });
{ "_id" : "mike", "display_name" : "Mike D" }
{ "_id" : 5, "author" : "mike", "text" : "MongoDB is fun!" }
Driver Support for DBRefs
One thing that can be confusing about DBRefs is that not all drivers treat them as normal
embedded documents. Some provide a special type for DBRefs that will be automati-
cally translated to and from the normal document representation. This is mainly pro-
vided as a convenience for developers, because it can make working with DBRefs a little
less verbose. As an example, here we represent the same note as earlier using PyMongo
and its DBRef type:
>>> note = {"_id": 20, "author": "kristina",
... "text": "... and DBRefs are easy, too",
... "references": [DBRef("users", "mike"), DBRef("notes", 5)]}
When the note is saved, the DBRef instances will automatically be translated to the
equivalent embedded documents. When the note is returned from a query, the opposite
will happen, and we'll get DBRef instances back.
Some drivers also add other helpers for working with DBRefs, like methods to handle
dereferencing or even mechanisms for automatically dereferencing DBRefs as they are
returned in query results. This helper functionality tends to vary from driver to driver,
so for up-to-date information on what's supported, you should reference driver-specific
documentation.
When Should DBRefs Be Used?
DBRefs are not essential for representing references to other documents in MongoDB.
In fact, even the previous example does some referencing using a different mechanism:
the "author" key in each note just stores the value of the author document's "_id" key.
We don't need to use a DBRef because we know that each author is a document in the
users collection. We've seen another example of this type of referencing as well: the
"files_id" key in GridFS chunk documents is just an "_id" reference to a file document.
With this option in mind, we have a decision to make each time we need to store a
reference: should we use a DBRef or just store an "_id" ?
Storing "_id" s is nice because they are more compact than DBRefs and also can be a
little more lightweight for developers to work with. DBRefs, on the other hand, are
 
Search WWH ::




Custom Search