【发布时间】:2019-05-09 09:18:40
【问题描述】:
我正在执行以下 mongodb 查询我是 mongo db 的新手,请告诉我我做错了什么
db.entityCounter.aggregate([
{
$lookup:
{
from: "fields",
localField: "code",
foreignField: "fieldCode",
as: "fieldsresult"
}
},{
$match:{
$and: [{
"fieldsresult.isVisible":"1"
},{"type":"field"
}]
}
}])
下面是java spring代码
LookupOperation lookupOperation = LookupOperation.newLookup()
.from("fields")
.localField("code")
.foreignField("fieldCode")
.as("fieldsresult");
AggregationOperation match1 = Aggregation.match(Criteria.where("fieldsresult.isVisible").is("1"));
// AggregationOptions aggregationOptions = Aggregation.newAggregationOptions();
DBObject ob=new BasicDBObject();
((BasicDBObject) ob).put("batchSize",10);
Aggregation aggregation = Aggregation.newAggregation(lookupOperation,match1).withOptions(Aggregation.newAggregationOptions().cursor(ob).build());
long val=0;
try {
AggregationResults<EntityCounter> result = mongoOperations.aggregate(aggregation, Fields.class, EntityCounter.class);
// val= result.getMappedResults();
}catch (Exception e){
e.printStackTrace();
}
但我遇到了错误
org.springframework.dao.InvalidDataAccessApiUsageException:命令执行失败:错误[需要'cursor'选项,除了带有解释参数的聚合],Command = {“聚合”:“实体计数器”,“管道”:[ {“$match”:{“fieldsresult.isVisible”:“1”}},{“$lookup”:{“from”:“fields”,“localField”:“code”,“foreignField”:“fieldCode”, "as" : "fieldsresult"}}]};嵌套异常是 com.mongodb.MongoCommandException:命令失败,错误 9:“需要 'cursor' 选项,除了带有解释参数的聚合”在服务器 localhost:27017 上。完整的响应是 { "ok" : 0.0, "errmsg" : "'cursor' 选项是必需的,除了带有解释参数的聚合", "code" : 9, "codeName" : "FailedToParse" }
【问题讨论】:
-
你使用的mongodb版本是什么
-
而且聚合有多个管道,你需要在聚合内部而不是外部使用匹配
-
尝试使用可用于聚合查询管道的游标选项:游标:{batchSize:
}..有用的链接:a)stackoverflow.com/questions/47472688/…b)docs.mongodb.com/manual/reference/method/… -
你确定它是正确的版本吗? Lookup support 从 1.9 版本开始添加到 spring mongo 中。此外,我 无法 使用 1.9 或任何其他版本重现该错误。你能创建一个[最小、完整和可验证的例子](stackoverflow.com/help/mcve)吗?一个 github 项目会很有帮助。
-
不可能。查找仅从 1.9 开始可用。所以你在使用1.8的时候就不能用了。按照建议,请提供可以重现错误的完整示例。
标签: java spring mongodb mongodb-query spring-data-mongodb