Java 使用MongoOperation在Spring数据MongoDB中更新构建阵列过滤器
我使用的是Spring bootJava 使用MongoOperation在Spring数据MongoDB中更新构建阵列过滤器,java,spring,mongodb,nosql,spring-mongodb,Java,Spring,Mongodb,Nosql,Spring Mongodb,我使用的是Spring boot2.2.1.RELEASE。如何使用Spring MongoOperation编写下面的MongoDB更新查询 db.cities.updateOne( { _id : ObjectId("5e78ec62bb5b406776e92fac") }, { $inc: { "subscriptions.$[category].subscribers" : 1, "subscriptions.$[category]
2.2.1.RELEASE
。如何使用Spring MongoOperation编写下面的MongoDB更新查询
db.cities.updateOne(
{
_id : ObjectId("5e78ec62bb5b406776e92fac")
},
{
$inc: {
"subscriptions.$[category].subscribers" : 1,
"subscriptions.$[category].options.$[option].subscribers" : 1
}
},
{ multi: true,
arrayFilters: [
{ "category._id": {$in: ["1", "2"]} },
{ "option.name": {$in: ["Time", "Gourmand", "Politics", "Entrepreneurship"]} }
]
}
)
我试过以下方法
Update update = new Update().inc("subscriptions.$[category].subscribers", 1).inc("subscriptions.$[category].options.$[option].subscribers", 1).filterArray(Criteria.where("category._id").in(Arrays.asList("1", "2")).andOperator(Criteria.where("option.name").in(Arrays.asList("Time", "Gourmand", "Politics", "Entrepreneurship"))));
UpdateResult result = mongoOperations.updateFirst(new Query(where("id").is(cityId)), update, CitiesDoc.class);
但我一直得到以下错误
org.springframework.dao.InvalidDataAccessApiUsageException:命令失败,错误为9(FailedToParse):“更新操作中无法识别的字段:arrayFilters”(服务器本地主机:56740)。完整响应为{“确定”:0.0,“errmsg”:“更新操作中无法识别的字段:arrayFilters”,“代码”:9,“代码名”:“FailedToParse”};嵌套异常为com.mongodb.MongoCommandException:命令失败,错误为9(FailedToParse):“更新操作中的字段无法识别:服务器本地主机:56740上的arrayFilters”。完整响应为{“确定”:0.0,“errmsg”:“更新操作中无法识别的字段:arrayFilters”,“代码”:9,“代码名”:“FailedToParse”}
不确定给出错误的字段。一些建议会很有帮助。它与以下查询一起工作
update = update.inc("subscriptions.$[category].subscribers", 1);
update = update.inc("subscriptions.$[category].options.$[option].subscribers", 1);
update = update.filterArray(Criteria.where("category._id").in(Arrays.asList("1", "2")));
update = update.filterArray(Criteria.where("option.name").in(Arrays.asList("Time", "Gourmand", "Politics", "Entrepreneurship")));
UpdateResult result = mongoOperations.updateFirst(new Query(where("id").is(cityId)), update, CitiesDoc.class);
但是错误的原因是MongoDB版本。我正在使用as嵌入式MongoDB进行测试。默认的MongoDB版本是3.5.5。我认为它不支持
阵列过滤器
。将版本更新为4.x解决了此问题。您可以了解如何将版本更新为最新支持的生产版本。将以下内容添加到应用程序。yaml
:
spring:
mongodb:
embedded:
version: 4.0.2