Database Reference
In-Depth Information
$addresses = $db->addresses;
// Specify an address
$address = array(
"Street" => "St. Annastraat 44",
"Place" => "Monster",
"Postal Code" => "2681 SR",
"Country" => "Netherlands"
);
// Save the address
$addresses->insert($address);
// Add a contact living at the address
$contact = array(
"First Name" => "Melvyn",
"Last Name" => "Babel",
"Age" => 35,
"Address" => $address['_id']
);
$people->insert($contact);
Now assume you want to find the preceding contact's address information. To do this, simply query for the
Object ID in the address field; you can find this information in the addresses collection (assuming you know the
name of this collection).
This works, but the preferred method for referencing another document relies on DBRef. This is because DBRef
relies on a common format that the database and all the drivers understand. We'll look at a DBRef version of the
preceding example momentarily. Before doing so, however, let's take a look at the create() function of the DBRef
class; you will use this class to create the desired reference.
The create() function takes three parameters:
collection : Specifies the name of the collection where the information resides (without the
database name).
id : Specifies the ID of the document to link to.
database : Specifies the name of the database in which the document resides.
The following example uses the create() function to create a reference to an address in another document:
// Connect to the database
$c = new Mongo();
$db = $c->contacts;
// Select the collections we want to store our contacts and addresses in
$people = $db->people;
$addresses = $db->addresses;
// Specify an address
$address = array(
"Street" => "WA Visser het Hooftlaan 2621",
"Place" => "Driebergen",
"Postal Code" => "3972 SR",
"Country" => "Netherlands"
);
 
Search WWH ::




Custom Search