使用 $where 和 MongoDB 的 Grails 查询

Grails query using $where with MongoDB

有没有办法在 Grails/GORM 中使用 $where 指令查询 mongo?

我正在尝试 运行 mongo 查询,类似于以下内容:

db.myAwesomeCollection.find({
    $where : function() { 
        /* Do Something Really Special */
        return true; // or false
    }
});

目前,我已将 mongoOperations bean 添加到 resources.xml 文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd        http://www.springframework.org/schema/data/mongo        http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

<mongo:mongo id="myreplicaset" replica-set="${grails.mongo.replicaSet}">
    <mongo:options
            connections-per-host="300"
            threads-allowed-to-block-for-connection-multiplier="5"
            connect-timeout="10000"
            max-wait-time="120000"
            auto-connect-retry="true"
            socket-keep-alive="false"
            socket-timeout="0"
            slave-ok="false"
            write-number="0"
            write-timeout="0"
            write-fsync="false"/>
</mongo:mongo>

<mongo:db-factory dbname="${grails.mongo.databaseName}" id="mongoDbFactory" mongo-ref="myreplicaset"/>

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongoDbFactory"/>
    <property name="writeResultChecking" value="EXCEPTION"/>
</bean>

<alias name="mongoTemplate" alias="mongoOperations"/>

然后在我的控制器中,我注入了 mongoOperations 对象:

def mongoOperations;

然后我可以直接在 mongoOperations bean 上调用 find() 操作。

String function = "function() { " +
    "return // true if the row matches your criteria" +
    "}";

Query query = new BasicQuery("{$where : \"" + function + "\"}");
List<MyDomainClass> results = mongoOperations.find(query, MyDomainClass.class);