Database Reference
In-Depth Information
■
When removing a document, you need to remember that any reference to that document will remain
within the database. For this reason, be sure you manually delete or update those references as well; otherwise, these
references will return null when evaluated. referencing will be discussed in the next section.
Warning
If you want to remove an entire collection, you can use the
drop()
function. The following snippet removes the
entire
newname
collection, including all of its documents:
> db.newname.drop()
true
The
drop()
function returns either
true
or
false
, depending on whether the operation has completed
successfully. Likewise, if you want to remove an entire database from MongoDB, you can use the
dropDatabase()
function, as in this example:
> db.dropDatabase()
{ "dropped" : "library", "ok" : 1 }
Note that this snippet will remove the database you are currently working in (again, be sure to check
db
to see
which database is your current database).
Referencing a Database
At this point, you have an empty database again. You're also familiar with inserting various kinds of data into a
collection. Now you're ready to take things a step further and learn about
database referencing
. As you've already
seen, there are plenty of scenarios where embedding data into your document will suffice for your application (such as
the track list or the list of authors in the topic entry). However, sometimes you do need to reference information in
another document. The following sections will explain how to go about doing so.
Just as with SQL, references between documents in MongoDB are resolved by performing additional queries on
the server. MongoDB gives you two ways to accomplish this: referencing them manually or using the DBRef
standard, which many drivers also support.
Referencing Data Manually
The simplest and most straightforward way to reference data is to do so manually. When referencing data manually,
you store the value from the
_id
of the other document in your document, either through the full ID or through a
simpler common term. Before proceeding with an example, let's add a new document and specify the publisher's
information in it (pay close attention to the
_id
field:
> apress = ( { "_id" : "Apress", "Type" : "Technical Publisher", "Category" :
["IT", "Software","Programming"] } )
{
"_id" : "Apress",
"Type" : "Technical Publisher",