使用MongoDB中的$ where查询Grails

时间:2015-01-19 21:10:18

标签: mongodb grails gorm

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

我尝试运行mongo查询,如下所示:

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

1 个答案:

答案 0 :(得分:0)

目前,我已经将一个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);