【问题标题】:mongodb wildcard query from grails/groovy来自 grails/groovy 的 mongodb 通配符查询
【发布时间】:2013-01-11 09:00:58
【问题描述】:

我在从 Grails 应用程序在 MongoDB 中发出通配符查询时遇到了一些问题。

基本上我现在的做法是发出带有查询参数数组的find 查询:

db.log.find(criteria)    -> where criteria is an array [testId:"test"]

只要我严格查询实际值,它就可以正常工作。但是,为了好玩,我尝试使用通配符搜索:

db.log.find(criteria) -> this time critera = [testId:/.*te.*/]

然而,在查看 Mongo 查询日志后,这将是:

 query: { query: { testId: "/.*te.*/" }

因此使查询不是通配符搜索,而是作为字符串查询。 有没有办法在某种意义上仍然使用这种查询概念来解决这个问题?

提前致谢!

【问题讨论】:

    标签: mongodb grails groovy


    【解决方案1】:

    使用 Groovy 模式快捷方式 ~ 指定您的查询是正则表达式。

    db.log.find(['testId': ~/.*te.*/])
    

    查看blog post了解更多信息

    【讨论】:

      【解决方案2】:

      要使用正则表达式查询,请使用 $regex operator 定义查询条件

      def regexCondition = ['$regex': '/.*te.*/']
      def criteria = ['testId': regexCondition]
      db.log.find(criteria)
      

      【讨论】:

      • 这不会返回我从 mongo 控制台运行它的任何东西。 db.log.find( { testId: { $regex: '/.*te.*/' } } )
      • mongo 将查询解释为字符串,删除 '',db.log.find({testId:{ $regex: /.*te.*/}}) 的问题仍然相同工作正常
      • @dunnless db.log.find({testId:{ $regex: /.*te.*/}}) 好像是mongodb控制台中的命令,但在Grails中,参数必须先放入BasicDBObject对象中。
      【解决方案3】:

      这对我有用: 在你的 groovy 文件中:

      db.collectionName.find([fieldName:[$regex:'pattern']])
      

      或多或少,使用常规的 mongodb 查询,但将 {} 替换为 []。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-05
        • 1970-01-01
        • 2012-02-10
        • 1970-01-01
        • 1970-01-01
        • 2013-04-21
        相关资源
        最近更新 更多