我在Grails控制器中有以下代码,它返回预期的结果:
def alm = SiteHistory.collection.find([
"phoneNumber":"${params.phoneNumber}",
"fields.P2Running":true])
.limit(20).toArray()
但是,我想根据输入参数修改搜索。当params.alarm ==“P2Running”
时,后续查询不返回任何文档def fieldsSelect = "fields."+params.alarm
def alm = SiteHistory.collection.find([
"phoneNumber":"${params.phoneNumber}",
fieldSelect:true])
.limit(20).toArray()
我也尝试过:
def fieldsSelect = "fields."+params.alarm
def alm = SiteHistory.collection.find([
"phoneNumber":"${params.phoneNumber}",
"${fieldSelect}":true])
.limit(20).toArray()
产生
Message: org.codehaus.groovy.runtime.GStringImpl cannot be cast to java.lang.String
at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:134)
at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:86)
at com.mongodb.DefaultDBEncoder.writeObject(DefaultDBEncoder.java:27)
at com.mongodb.OutMessage.putObject(OutMessage.java:142)
at com.mongodb.OutMessage._appendQuery(OutMessage.java:85)
at com.mongodb.OutMessage.query(OutMessage.java:44)
at com.mongodb.OutMessage.query(OutMessage.java:38)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:303)
at com.mongodb.DBCursor._check(DBCursor.java:369)
at com.mongodb.DBCursor._hasNext(DBCursor.java:498)
at com.mongodb.DBCursor._fill(DBCursor.java:558)
at com.mongodb.DBCursor.toArray(DBCursor.java:596)
at com.mongodb.DBCursor.toArray(DBCursor.java:584)
at remote.SiteHistoryController$_closure2$$EO0HJb0Z.doCall(SiteHistoryController.groovy:58)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
我的域名对象是
class SiteHistory {
ObjectId id
String phoneNumber
Date receiveDate=null
Map<String,Object> fields = [:]
static mapWith = "mongo"
}
在添加数据之前,不会知道字段中的字符串键。
示例文档是:
{
"_id" : ObjectId("513eaefe290b3700b8e2c966"),
"phoneNumber" : "1234567890",
"receiveDate" : "Wed Mar 06 2013 23:52:47 GMT-0500 (EST)",
"fields" : {
"P1Runtime" : 37.6,
"P1Starts" : 23,
"P1Running" : false,
"P2Runtime" : 35.7,
"P2Starts" : 25,
"P2Running" : true,
"WetWellLvl" : 10,
"HighLvlAlarm" : false
}
}
为什么从params创建的字符串不起作用的任何想法?
答案 0 :(得分:0)
以下是适用于Grails 2.0.1和Mongodb 1.0.0.RC4的代码:
def query = new BasicDBObject("phoneNumber", params.phoneNumber)
.append("fields.${params.alarm}", true)
def alm = SiteHistory.collection.find(query).limit(20).toArray()
我没有尝试使用Criteria,因为我读到了某些地方,他们没有使用mongodb对象。但是,我确实有namedQueries正在处理这个对象。所以我尝试了一个标准和IT工作! (注意:它适用于Grails 2.2.1和mongodb 1.2.0。)
以下是代码:
def c = SiteHistory.createCriteria()
def alm = c.list (max:20, offset:0) {
eq ("phoneNumber", params.phoneNumber)
eq ("fields.${params.alarm}", true)
}
我在Grails 2.2.1中还有其他问题,所以我还没有升级。