Appendix D. MongoDB in PHP, Java, and C++

 

This book 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 book. Plus, the Java driver’s API diverges significantly 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 developers wanting to build high-performance standalone applications.

Each language section describes how to construct documents and make connections, 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 produce 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 equivalent Ruby code.

D.1.1. Documents

D.2. Java

D.3. C++

sitemap