Database Reference
In-Depth Information
// Save the address
$addresses->insert($address);
// Create a reference to the address
$addressRef = MongoDBRef::create($addresses->getName(), $address['_id']);
// Add a contact living at the address
$contact = array(
"First Name" => "Ivo",
"Last Name" => "Lauw",
"Age" => 24,
"Address" => $addressRef
);
$people->insert($contact);
Note
the getName() function in this example is used to get the name of the collection.
Retrieving the Information
So far you've used DBRef to create a reference. Now it's time to look at how to retrieve the information referenced,
so that you can display the contents again correctly. You do this using MongoDBRef 's get() function.
MongoDBRef 's get() function takes two parameters. The first parameter specifies the database to use, while the
second provides the reference to fetch:
// Connect to the database
$c = new Mongo();
// Select the collection 'people' from the database 'contacts'
$people = $c->contacts->people;
// Define the search parameters
$lastname = array("Last Name" => "Lauw");
// Find our contact, and store under the $person variable
$person = $people->findOne(array("Last Name" => "Lauw"));
// Dereference the address
$address = MongoDBRef::get($people->db, $person['Address']);
// Print out the address from the matching contact
print_r($address);
The resulting output shows the document being referred to:
Array (
[_id] => MongoId Object ( )
[Street] => WA Visser het Hooftlaan 2621
[Place] => Driebergen
[Postal Code] => 3972 SR
[Country] => Netherlands
)
DBRef provides a great way to store data you want to reference, not least because it permits flexibility in the
collection and database names.
 
 
Search WWH ::




Custom Search