I was dipping my toes in NoSQL MangoDB past week or so. It made me feel like an elephant born in to captivity suddenly let wonder as free without unyielding rules, traditions and frameworks. It was exciting, adventurous but we used to rules, we like them; they make us feel safe and warm.
My last week spent on trying to figure out what is the best way to connect to MongoDB with ColdFusion. Adobe ColdFusion does not support MongoDB natively yet. There are two projects in riaforge that we can use to connect to MongoDB with ColdFusion 9 or higher. CFMongoDB and MongoCFC, they both use MongoDB java Driver and provide set of functions similar to MongoDB but slightly different syntax time to time. For example MongoCFC use the syntax getCollection() and CFMongoDB use getDBCollection(). Open BD introduced number of new functions and Railo 4.1 will have native support tweeted the lord of Railo Gert Franz. This makes me wonder would this be another important juncture where all three ColdFusion engines would create their own dialects. That worried me a bit.
One thing is sure, ColdFusion/Railo/OBD, they all will use MongoDB Java API. The problem is ColdFusion data types and MondoDB data types do not see eye to eye most of the times. Therefor a middle man is needed to do bit of data exchange. CFMongoDB and MongoCFC do that. It covert ColdFusion data types into MongoDB and other way around. But since database connectivity is one of the major components in any application, if not the biggest, it is always good to have as much as raw control you can get. Even if ColdFusion come up with MongoDB related functions, it is always good to have full control. It is sort of like been able to write your own Queries while having CFSELECT tag or been able to create your own JavaScript grid while been able to use CFGRID.
So I jump directly into Java Driver and looks around to find a way to use it straight.
Luckily MongoDB Java API comes with a JSON to MongoDB data type conversion utility. Now there is our middle man. JSON. We can convert our ColdFusion data types to JSON using SerializeJSON() (or cfjson,jsonutil) and use the MongoDB utility to convert that into MongoDB data type. There you have tremendous control. It would be nice to have updated JavaCast() function that can convert data into a “MongoDB” type. But until all three engines settle down on set of new syntex, we can create our own little function to do the business. Also once you are quite familiar with the Java API, you can go back to CFMongoDB or MongoCFC and start contributing too or you can create your own set of functions.
Here is my experimented code sheet. As you can see, I use exact MongoDB syntax. So there is no need to learn same thing twice.
Note : For some reason Gist embed code block is loosing formating. View it here directly.