OpenBD and MongoDB: Can’t get easier then this

I’m currently working on a project that uses MongoDB (yes, that’s the awesome NoSQL database everyone talks about). Now, my favorites language of choice (CFML) and especially my favorite open source CFML engine OpenBD, has support for MongoDB built in which makes it a snap to use for any ColdFusion developer.

MongoDB’s query syntax is quite different then the SQL you might got used to. A good overview how to find (select) records with MongoDB can be found at SQL to Mongo Mapping Chart. In short, the MongoDB find() syntax is close to the “chained” commands you might know from the likes of JQuery. Important to remember is that 99% of the time everything you pass to MongoDB is a JSON structure and has a JSON like syntax.

Since OpenBD is using the Java Driver and we apply a CFML tag for it, the query syntax differs slightly from the one you would enter in a mongo shell. Please find below some examples.

Find all records

<cfset myarray = MongoCollectionfind(
   datasource="mongosource", 
   collection="users", 
   query={}
)>

The above MongoCollectionfind() will return an Array with all records of the Collection and all fields.

Return only certain fields

It’s a common practice not to return all fields as in a “SELECT column1, column2 FROM…”. With MongoCollectionfind() you would do something like:

<cfset myarray = MongoCollectionfind(
datasource="mongosource",
collection="users",
query={},
fields={email:true,firstname:true}
)>

Again the MongoCollectionfind() would return an Array with all records, but this time only with the columns “email” and “firstname”. Note: The unique value of “_id” is always returned!

Find a specific user

Of course, returning all records is 99% of the time not wanted. MongoDB has a very sophisticated approach to finding records. As you can see from the SQL to MongoDB map. Ok, now let’s find user by his eMail address.

<cfset myarray = MongoCollectionfind(
datasource="mongosource",
collection="users",
query=({email:"nitai@openbd.com"}),
fields={email:true,firstname:true}
)>

To find the user with his eMail address AND his first name you would do:

<cfset myarray = MongoCollectionfind(
datasource="mongosource",
collection="users",
query=({email:"nitai@openbd.com",firstname:"nitai"}),
fields={email:true,firstname:true}
)>

The same find() as above but this time with OR would be:

<cfset myarray = MongoCollectionfind(
datasource="mongosource",
collection="users",
query=( { $or : [ { email : "nitai@openbd.com" } , { first_name : "nitai" } ] } ),
fields={email:true,firstname:true}
)>

As you can see form the examples above, working with OpenBD and the MongoDB syntax is straight forward and easy. Hope this helps.