spring boot mongodb templete 两个字段比较查询

mac2026-05-23  5

使用MongoTemplete比较两个字段比较麻烦(类似SQL select * from db where quantity>finish) 1,Spring data MongoDB 目前不支持 $expr 2,可行的方式之一是利用project 和 $cond(MongoTemplet也不直接支持 $cond,要用到AggregationSpELExpression) 参考: 上代码:

Aggregation aggregation = newAggregation(project("quantity", "finish") .and(AggregationSpELExpression.expressionOf("cond(quantity>finish, 1, 0)")).as("flag1") ,match(Criteria.where("flag1").is(1))); list = MongoTemplate.aggregate(aggregation, "xxxx", xxx.class).getMappedResults();

先添加一个字段(flag1)存比较结果,再按比较结果过滤。

ps:话说mongodb资料好少啊,这么小问题整了一个下午

最新回复(0)