Querying MongoDB from Clojure using regex Prefix matches

by Wolfram Saringer  (2011-04-15)
last change: 2011-04-15


Turns out to be quite simple... Assuming a collection with an indexed attribute called 'index' the code would look something like this:

(ns test
(:use somnium.congomongo))

(def mongo-server "mongo.test")
(def mongo-db "testdb")
(def mongo-collection "indexedtestcollection")

(defn find-test [input]
(mongo!
:host mongo-server
:db mongo-db )
(let [rx (. Pattern compile (str "^" (first input)))]
(println (.getName (.getClass rx)))
(take 3
(fetch mongo-collection
:where {:index rx}
)
)
)
)

The main point being that the value for rx must be a Regex instance. In this sample code the regex is dynamically created, using a static #"^regex" works as well.

MongoDB can only use the index on the column if the regex is a prefix match (i.e. uses the '^' anchor).



all articles represent the sole opinion of their respective author. all content comes without any warranty for correctnes, despite due diligence.