Databases Reference
In-Depth Information
Database References
Perhaps one of the least understood features of MongoDB is its support for
database
references
, or
DBRefs
. DBRefs are like URLs: they are simply a specification for uniquely
identifying a reference to document. They do not automatically load the document any
more than a URL automatically loads a web page into a site with a link.
What Is a DBRef?
A DBRef is an embedded document, just like any other embedded document in
MongoDB. A DBRef, however, has specific keys that must be present. A simple example
looks like the following:
{"$ref" :
collection
, "$id" :
id_value
}
The DBRef references a specific
collection
and an
id_value
that we can use to find a
single document by its
"_id"
within that collection. These two pieces of information
allow us to use a DBRef to uniquely identify and reference any document within a
MongoDB database. If we want to reference a document in a different database, DBRefs
support an optional third key that we can use,
"$db"
:
{"$ref" :
collection
, "$id" :
id_value
, "$db" :
database
}
DBRefs are one place in MongoDB where the order of keys in a docu-
ment matters. The first key in a DBRef must be
"$ref"
, followed by
"$id"
, and then (optionally)
"$db"
.
Example Schema
Let's look at an example schema that uses DBRefs to reference documents across col-
lections. The schema consists of two collections,
users
and
notes
. Users can create notes,
which can reference users or other notes. Here are a couple of user documents, each
with a unique username as its
"_id"
and a separate free-form
"display_name"
:
{"_id" : "mike", "display_name" : "Mike D"}
{"_id" : "kristina", "display_name" : "Kristina C"}
Notes are a little more complex. Each has a unique
"_id"
. Normally this
"_id"
would
probably be an
ObjectId
, but we use an integer here to keep the example concise. Notes
also have an
"author"
, some
"text"
, and an optional set of
"references"
to other notes
or users:
{"_id" : 5, "author" : "mike", "text" : "MongoDB is fun!"}
{"_id" : 20, "author" : "kristina", "text" : "... and DBRefs are easy, too",
"references": [{"$ref" : "users", "$id" : "mike"}, {"$ref" : "notes", "$id" : 5}]}
The second note contains some references to other documents, each stored as a
DBRef. Our application code can use those DBRefs to get the documents for the “mike”