I am trying to perform a wildcard search in Mongo using ColdFusion 11 & The Java MongoDB driver 3.8 on MongoDB 4.0.
The following code gives me errors saying that the method countDocuments()
cannot be found or the method find()
cannot be found.
<cfset Mongo = CreateObject("java","com.mongodb.MongoClient").init("localhost")>
<cffunction name="m" returntype="any">
<cfargument name="value" type="any">
<cfif IsJSON(arguments.value)>
<cfset local.retrun = CreateObject("java","com.mongodb.util.JSON").parse(arguments.value)>
<cfelse>
<cfset local.retrun = CreateObject("java","com.mongodb.util.JSON").parse( SerializeJSON(arguments.value) )>
</cfif>
<cfreturn local.retrun>
</cffunction>
<cfset db = Mongo.getDatabase('fda')>
<cfset DrugInfo = db.getCollection("druginfo")>
<cfset searchCount=druginfo.countDocuments(m({'openfda.brand_name':/Ty/ }))>
<cfset results = DrugInfo.find(m({'openfda.brand_name': /Ty/})).iterator()>
When attempting to do an exact match search, everything works fine.
<cfset searchCount=druginfo.countDocuments(m({'openfda.brand_name':'Tylenol'}))>
<cfset results = DrugInfo.find(m({'openfda.brand_name': 'Tylenol'})).iterator()>
I'm basically testing all my queries in Mongo Compass and pasting them into my code but it's not coming working as expected.
That error message is not very descriptive.
The Java driver won't take regex'es (or at least not via ColdFusion objects) like Compass does, so you'll have to $regex
with the pattern between quotes like:
{ <field>: { $regex: 'pattern', $options: '<options>' } }
For example instead of
m({'openfda.brand_name':/Ty/ })
use
m({ 'openfda.brand_name': { '$regex': '^Ty', '$options': 'i' } })
There is more about how to use $regex
here:
(https://docs.mongodb.com/manual/reference/operator/query/regex/)