【问题标题】:Use of search patterns with monger与 monger 一起使用搜索模式
【发布时间】:2015-12-02 08:36:13
【问题描述】:

我希望使用这样的搜索模式从 clojure 访问 mongo db:

find({Keywords: /search-pattern/})

我有一个名为“soulflyer”的数据库,其中包含一个“图像”集合,每个成员都有一个“关键字”字段,其中包含来自它所代表的图像的 exif 关键字数组。 要从 mongo java shell 中搜索自己的图像,我会这样做:

db.getCollection('images').find({Keywords: "Iain Wood"})

然后我得到一个包含关键字“Iain Wood”的所有条目的列表。如果我在 repl 中这样做,这在 clojure 中也可以正常工作:

(def connection (mg/connect))
(def db (mg/get-db connection "soulflyer"))
(seq (mc/find db "images" {"Keywords" "Iain Wood"}))

但是,我想搜索关键字的部分匹配项。这在 java shell 中可以正常工作,使用如下命令:

db.getCollection('images').find({Keywords: /Iain/})

正如预期的那样,我取回了包含“Iain”关键字的所有图像。但是我找不到如何从 clojure 进行这项工作。

(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\/}))
(seq (mc/find db "images" {"Keywords" "\/Iain\/"}))

给我一​​个 LispReader$ReaderException 或冻结 repl。

如何让 clojure/monger 搜索简单的模式匹配?

【问题讨论】:

    标签: mongodb clojure monger


    【解决方案1】:

    我不确定 monger 是否支持这种开箱即用的子字符串模式匹配,但您可以轻松地使用正则表达式。这记录在mongers query documentation 中。您需要使用$regex 运算符。像下面这样的东西应该可以工作:

      (mc/find db "images" {"Keywords" {$regex ".*Iain.*"}})
    

    【讨论】:

    • 这行得通,谢谢。我曾希望使用更简单更优雅的模式匹配语法,但正则表达式会完成这项工作......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 2018-07-03
    • 2017-01-25
    相关资源
    最近更新 更多