Database Reference
In-Depth Information
To obtain the information itself, you combine the findOne function with some dot
notation:
> db.publisherscollection.findOne( { _id : book.Publisher } )
{
"_id" : "Apress",
"Type" : "Technical Publisher",
"Category" : [
"IT",
"Software",
"Programming"
]
}
As this example illustrates, referencing data manually is straightforward and doesn't
require much brainwork. Here, the _id in the documents placed in the users collection
has been manually set and has not been generated by MongoDB (otherwise, the _id
would be an object ID).
Referencing Data with DBRef
The DBRef standard provides a more formal specification for referencing data between
documents. The main reason for using DBRef over a manual reference is that the
collection can change from one document to the next. So, if your referenced collection
will always be the same, the referencing data manually (as just described) is fine.
With DBRef, the database reference is stored as a standard embedded (JSON/
BSON) object. Having a standard way to represent references means that drivers and data
frameworks can add helper methods that manipulate the references in standard ways.
The syntax for adding a DBRef reference value looks like this:
{ $ref : <collectionname> , $id : <id value> [, $db : <database name> ] }
Here, <collectionname> represents the name of the collection referenced (for
example, publisherscollection ); <id value> represents the value of the _id field for
the object you are referencing; and the optional $db allows you to reference documents
that are placed in other databases.
Let's look at another example using DBRef from scratch. Begin by emptying your two
collections and adding a new document:
> db.publisherscollection.drop()
true
> db.media.drop()
true
> apress = ( { "Type" : "Technical Publisher", "Category" :
 
Search WWH ::




Custom Search