Database Reference
In-Depth Information
appendix D
MongoDB in PHP,
Java, and C++
This topic has presented MongoDB through the lenses of JavaScript and Ruby. But
there are plenty of other ways to communicate with MongoDB, and this appendix
presents three that span the gamut. I'll start with PHP because it's a popular scripting
language. I include Java because it's still arguably the language of the enterprise and
thus important to a lot of readers of this topic. Plus, the Java driver's API diverges sig-
nificantly from that of most scripting languages. Finally, I'll present the C++ driver
because it's a core part of MongoDB's codebase, and it's likely to be useful to develop-
ers wanting to build high-performance standalone applications.
Each language section describes how to construct documents and make connec-
tions, and then ends with a complete program that inserts, updates, queries, and
deletes a sample document. All of the programs perform the same operations and pro-
duce the same output, so they're easy to compare. The document in each program is
an example of what a simple web crawler might store; for reference, here it is in JSON :
{ url: "org.mongodb",
tags: ["database", "open-source"],
attrs: { "last-visit" : ISODate("2011-02-22T05:18:28.740Z"),
"pingtime" : 20
}
}
D.1
PHP
The PHP community has embraced MongoDB with zeal, thanks in no small part to the
quality of the driver. The sample code should feel roughly isomorphic to the equiva-
lent Ruby code.
D.1.1
Documents
PHP arrays are implemented as ordered dictionaries. They therefore map nicely to
BSON documents. You can create a simple document using PHP array literals:
$basic = array( "username" => "jones", "zip" => 10011 );
266
Search WWH ::




Custom Search