I wish to access a mongo db from clojure using search patterns like this:
find({Keywords: /search-pattern/})
I have a database called "soulflyer", containing an "images" collection and each member has a "Keywords" field containing an array of exif keywords from the image it represents. To search for images of myself from the mongo java shell I do this:
db.getCollection('images').find({Keywords: "Iain Wood"})
and I get back a list of all the entries that contain the Keyword "Iain Wood". This also works fine in clojure, if I do this in the repl:
(def connection (mg/connect))
(def db (mg/get-db connection "soulflyer"))
(seq (mc/find db "images" {"Keywords" "Iain Wood"}))
However, I want to search for partial matches on keywords. This works ok from the java shell with a command like this:
db.getCollection('images').find({Keywords: /Iain/})
As expected, I get back all the images with a keyword that contains "Iain". However I can't find how to make this work from clojure.
(seq (mc/find db "images" {"Keywords" "/Iain/"}))
returns an empty list
(seq (mc/find db "images" {"Keywords" /Iain/}))
(seq (mc/find db "images" {"Keywords" '/Iain/'}))
(seq (mc/find db "images" {"Keywords" \/Iain\/}))
(seq (mc/find db "images" {"Keywords" "\/Iain\/"}))
give me a LispReader$ReaderException or freeze up the repl.
How do I get clojure/monger to search on a simple pattern match?
I'm not sure that monger supports this substring pattern match out of the box, but you can easily use regular expressions. This is documented in mongers query documentation. You need to use the $regex
operator. Something like the following should work:
(mc/find db "images" {"Keywords" {$regex ".*Iain.*"}})