我在MongoDB中有两个集合。我正在Jmeter中使用JSR223采样器在mongoDB上执行查找操作。
数据库名称: DB
收藏集名称: c_1,c_2
在MongoDB中执行查找聚合的Groovy代码。
c_1.insert(new BasicDBObject(["id" : 1, "name" : "abc", "lastName" : "kumar", "companyId": 10]))
c_2.insert(new BasicDBObject(["id" : 10, "companyName" : "Microsoft", "numEmployee" : 100 ]))
// build the $lookup operations
DBObject lookupFields = new BasicDBObject("from", "c_2");
lookupFields.put("localField", "companyId");
lookupFields.put("foreignField", "id");
lookupFields.put("as", "companydoc");
DBObject lookup = new BasicDBObject("$lookup", lookupFields);
// build the $project operations
DBObject projectFields = new BasicDBObject("name", 1);
projectFields.put("lastName", 1);
projectFields.put("companyId", 1);
projectFields.put("companyName", "$c_2.companyName");
DBObject project = new BasicDBObject("$project", projectFields);
List<DBObject> pipeline = Arrays.asList(lookup, project);
AggregationOutput output = c_1.aggregate(pipeline);
for (DBObject result : output.results())
{
System.out.println(result);
}
错误:响应消息:javax.script.ScriptException:groovy.lang.MissingPropertyException:无此类属性:查找类:Script79
答案 0 :(得分:1)
根据Groovy GStrings,您的语法与documentation不兼容:
如果您需要在GString中转义$或$ {}占位符,以使它们按原样显示而无需插值,则只需使用\反斜杠字符即可转义美元符号:
assert '${name}' == "\${name}"
所以要么使用单引号,例如:
DBObject lookup = new BasicDBObject('$lookup', lookupFields);
或用反斜杠转义美元符号:
DBObject lookup = new BasicDBObject("\$lookup", lookupFields);
$project
,$c_2.companyName
等的相同方法。