{ NAME: “Marc Esher”, TWEETER: WORK_FOR: “Booz | Allen | Hamilton”, CONTRIBUTE_TO: [ “MXUnit”, “CFMongoDB” ], URL: “ DATE: new Date(’11/12/2010’) } And I’m going to show you: why MongoDB is Awesome
Our Journey Pop Quiz Why MongoDB For CF-ers? The Feel of MongoDB Why MongoDB? Why Not MongoDB? Some more awesomeness CFMongoDB
What datatype is this?
And This?
And the first picture is different from that last one how? VS.
Mindshift From Queries To Arrays of Structures
MongoDB is… A Schema-less, Document-Oriented datastore Documents are roughly equivalent to CF structs: Keys, values Values can be other documents (i.e. embedded) Documents are searchable
MongoDB’s Data Model A Database has “Collections” Collections have “Documents” Documents have “Fields” Fields are key = value pairs A Collection does not enforce the structure of its documents* *i.e. Schemaless
Our Journey Pop Quiz Why MongoDB For CF-ers? The Feel of MongoDB Why MongoDB? Why Not MongoDB? Some more awesomeness CFMongoDB
Why MongoDB for CF-ers? “It’s so easy, even a ColdFusion ‘programmer’ can use it” -- anonymous PHP scriptmonkey
This time, with feeling Familiar Datatypes MongoDB Document == CF Struct MongoDB Collection == Arrays of Structs
And then…. Ad hoc queries “language” for querying these collections Secondary indexes to support these queries
MongoDB and ColdFusion 10gen (MongoDB makers) builds the Java drivers Drop the jars into your cfusion lib Or use JavaLoader Then use Mongo like any other object CFMongoDB can make all of this a breeze
Our Journey Pop Quiz Why MongoDB For CF-ers? Surprise Pop Quiz! The Feel of MongoDB Why MongoDB? Why Not MongoDB? Some more awesomeness CFMongoDB
What datatype is this? “2”
What datatype is this? “true”
What datatype is this? false
What datatype is this? {married=“true”, age=35}
It ain’t all puppies and unicorns 1 != “1” true != “true” != “2.546” {age=35} != {AGE=35} {lastname= 1,firstname= 1 } != {lastname: 1,firstname: 1 }* Lucky for you, CFMongoDB solves *most* of these problems * HUH? When we get to.sort(), you’ll see
Get your mind right Think in JavaScript When you’re creating CFML structures, pretend you’re creating JavaScript objects Case Matters Datatype matters (unless you use CFMongoDB)
Our Journey Pop Quiz Why MongoDB For CF-ers? The Feel of MongoDB Why MongoDB? Why Not MongoDB? Some more awesomeness CFMongoDB
The “Feel” of MongoDB Relax… we’ll do more bullet points later
Install and Run MongoDB Download from mongodb.org Unzip Create data directory >mkdir c:\data\db Run MongoDB (mongod): >cd c:\mongodb-1.6.3\bin >mongod Run Mongo shell (mongo): >mongo Yes, that’s it
The Mongo Shell >mongo >help() >show dbs >use >show collections >db.collectionName.findOne() >db.collectionName.find() >db.help() >db.collectionName.help()
Insert See that new “_id” field? We’ll discuss that later
Update
Remove
Finding by nested fields
Finding with Conditionals
What happens if I search on a field a Document doesn’t have?
Can I Find Documents without XXX?
Sorting? Limiting? Skipping? Have you ever had to “Page” in a web app?
Sorting? 1 = true, 1 = asc, 1 = include -1 = false, -1 = desc, -1 = exclude (depends on context)
Sorting? Limiting? sort(), skip(), limit()
Sorting + Limiting + Skipping = Paging sort(), skip(), limit()
count() and distinct()
And so much more!
Schema Design Guideline Embed when you can: { NAME = “Marc”, KIDS = [{NAME=“Lexie”}, {NAME=“Sidney”}] } Relate when you must: { NAME = “Marc”, KIDS = [ ObjectId(4cd0bcc b7dcfd6a), ObjectId(4cd0bcc b7dcfd7a) ] } (and watch the presentations, too)
Our Journey Pop Quiz Why MongoDB For CF-ers? The Feel of MongoDB Why MongoDB? Why Not MongoDB? Some more awesomeness CFMongoDB
Why MongoDB: The Official Word MongoDB is Big and Fast (just like every other NoSQL Datastore)
Why MongoDB: Performance No Joins + No multi-row transactions = Fast Reads = Fast Writes (b/c you write to fewer tables, no trans. log) Async writes = you don’t wait for inserts to complete (optional, though) Secondary Indexes = Index on embedded document fields for superfast ad-hoc queries Indexes live in RAM
Why MongoDB: Scalability / Availability No Joins + No multi-row transactions = Horizontally Scalable = Built for Distribution of data and computation Sharding for distributed data MapReduce for distributed computation Built-in Replication Easy to configure Reads can be distributed across slaves Automatic failover when using Replica Sets Shard for scalability, replicate for availability
Why MongoDB: R.A.D. Documents (think: objects) with embedded documents feel more natural compared with DB / ORM Ad-hoc queries don’t require “view” creation or other config… code-n-go No penalty for schema evolution (true for most NoSQL stores) Atomic Modifiers for safe in-place updates (no locking code around single documents) Built-in functions for Mongo-as-a-queue (I LOVE these!)
Why MongoDB: Friendly License You can use MongoDB in your corporate app You do not have to open source your corporate app From the docs: “ To reiterate, you only need to provide the source for the MongoDB server and not your application”
Why MongoDB: Marc’s Favorite Things Structs, how do I love thee? Inserts/Updates/Upserts are soooo easy Most days, I want to kneecap ORM… not so with Mongo Frequently “embedded” more natural than “relational” Queries, queries, queries. Indexes, Indexes, Indexes Functionality built for “paging”: sort, limit, skip, count, size Horizontal Scaling makes sense to me Docs are Fantastic Examples, examples, examples One word: findAndModify(). U-Ni-Corns MongoDB has brought Joy into my development
Our Journey Pop Quiz Why MongoDB For CF-ers? The Feel of MongoDB Why MongoDB? Why Not MongoDB? Some more awesomeness CFMongoDB
Why Not MongoDB? Vs. Relational DBs No Joins You’ll embed instead You’ll join in your application code when necessary No Transactions Might want to rethink using MongoDB for bank account transfers Though if you consider a “trade” as a single document representing both sides of the transaction… remember, mindshift You WILL miss SQL! Though you’ll get used to MapReduce (which is just JS functions!) Perhaps not a great fit for Reporting-heavy apps Though die-hards would debate this It simply may not be a best fit for your app Relational databases are not going anywhere CoSQL?
Why Not MongoDB? Vs. Itself Still kinda new Though used in production at major sites Evolving rapidly This is a good thing, though you’ll want to keep up with new releases Not meant for 32Bit You’ll have a 2GB limit per mongod process if you do No single-server durability If you’re not running replication, and it crashes, you will lose data (they’re working on this) Just replicate, period
Why Not MongoDB? Vs. ColdFusion 2 != “2” And fixing that is either: A) Ugly as hell: javacast(“int”, 2)… everywhere! B) slow(ish) if using CFMongoDB I get 1000 inserts on a raggedy-ass laptop
Our Journey Pop Quiz Why MongoDB For CF-ers? The Feel of MongoDB Why MongoDB? Why Not MongoDB? Some more awesomeness CFMongoDB
Awesome: Query Operators $ne: db.people.find( { NAME: { $ne: “Shaggy”} } ) $nin: db.people.find( { NAME: { $nin: [“Shaggy”, “Daphne”] } } ) $gt and $lt: db.people.find( AGE: { {$gt: 30, $lt: 35} } ) $size (eg, people with exactly 3 kids): db.people.find( KIDS: {$size: 3} ) regex: (eg, names starting with Ma or Mi) db.people.find( {NAME: /^M(a|i)/} ) More at
Awesome: Atomic Modifiers $inc db.pageviews.update( {URL: ‘ {$inc: {N: 1}} ) $set db.people.update( {NAME: ‘Steve’}, {$set: {Age: 35}} ) $push (for atomically adding values to an array) db.people.update( {NAME: ‘Steve’}, {$push: {KIDS: {NAME: ‘Sylvia’, AGE: 3}}}) findAndModify() db.tasks.findAndModify( query: {STATUS: ‘pending’}, sort: {PRIORITY: -1}, update: {$set: {STATUS: ‘running’, TS: new Date()}} ) More at
Awesome: ObjectId BSON (binary-encoded JSON) Unique: combination of Time Machine Process id Incrementer Mongo will automatically add this _id field Language-specific drivers automatically add this, too (BEFORE saving!) Your documents get a timestamp for free CFMongoDB has a function that gives it to you
Awesome: The DOCS RTFM
Our Journey Pop Quiz Why MongoDB For CF-ers? The Feel of MongoDB Why MongoDB? Why Not MongoDB? Some more awesomeness CFMongoDB
CFMongoDB: Description and Goals Description Founded by Bill Shelton, MXUnit founder on Twitter) Library for using MongoDB in CFML Supported on CF9.0.1 and Railo 3.2 Wraps around the Official MongoDB Java driver Goals “Smooth the rough edges” of CFML & MongoDB Query DSL for “joyful” querying and easier debugging 2 == “2”, dammit! “Struct transparency”: you save structs, you get structs Easy access to Java drivers so you can everything the Java drivers provide More to come (object persistence/mapping, etc)
CFMongoDB: Getting Started Download CFMongoDB and put in your webroot Install MongoDB and confirm it works It ships with the latest 10gen Java drivers It ships with Mark Mandel’s JavaLoader… you needn’t add any jars to your path Open examples/gettingstarted.cfm Inspect code Run code Rejoice
CFMongoDB: Init the Config object We need to create some Java objects. Who’s gonna do it? The “factory”: ooooooh, spoooooooky! In English: “Hey, ColdFusion”, create these java objects for me OR “Hey, JavaLoader, you create these objects cuz I don’t wanna put jars in my lib folder”
CFMongoDB: Init the Config object Typical CF You must put the mongo jar and cfmongodb jar in your cfusion/lib mongoConfig = createObject('component','cfmongodb.core.MongoConfig').init(dbName="mongorocks"); JavaLoader You don’t need to put any jars in your path javaloaderFactory = createObject('component','cfmongodb.core.JavaloaderFactory').init(); mongoConfig = createObject('component','cfmongodb.core.MongoConfig').init(dbName="mongorocks", mongoFactory=javaloaderFactory);
CFMongoDB: Init the Mongo object mongo = createObject('component','cfmongodb.core.Mongo').init(mongoConfig);
CFMongoDB: Saving
CFMongoDB: Querying
CFMongoDB: Search Result
CFMongoDB: Find by ObjectID
CFMongoDB: findAndModify()
CFMongoDB: Off you go! See cfmongodb/examples for search examples, master/detail examples, And more examples forthcoming
Resources Click “Try It Out” for an in-browser shell! Coding Docs: Admin Docs: Possibly the single best MongoDB resource next to the docs: More presentations Articles