spring-data-mongo aggregate 筛选两个字段相等

发布于 2022-09-04 08:09:49 字数 754 浏览 16 评论 0

在使用spring-data-mongo做统计时,需要比较两个字段是否相等,比如 l==qzt
就像find中查询

db.dbName.find({$where:"this.l=this.qzt"})

这段代码是能查询出来的
但是在使用spring-data-mongo Aggregation的时候 就报以下错误

"errmsg" : "$where is not allowed inside of a $match aggregation expression" , "code" : 16395

我是这样用的:

Criteria c = Criteria.where("$where").is("this.qzt==this.l");
Aggregation agg =Aggregation.newAggregation(
    Aggregation.match(c),
    Aggregation.group("qzc").count().as("z"),
    Aggregation.project("z").and("qzc").previousOperation(),
    Aggregation.sort(Sort.Direction.DESC, "z")
);
List<Events2> results = events2Data.agreagate(agg);

请问各位是哪里有错吗,或者,有什么方法能比较一下两个字段是否相等吗?拜谢~

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深府石板幽径 2022-09-11 08:09:49

很抱歉现在才来补充回答,此问题早已找到答案,就是用mongo-driver自带的aggregate方法,手动拼接查询语句,进行聚合查询,实现代码如下:

DBObject group = (DBObject) JSON.parse("{'$group': {'_id': {'qzc':'$qzc','qzt':'$qzt'},'z': {'$sum':1}}}");
DBObject project = (DBObject) JSON.parse("{'$project': {'z':1,'difference': { '$eq': [ '$l', '$qzt' ]}}}");
DBObject match = (DBObject) JSON.parse("{'$match': {'difference':true,'l':{'$ne':0}}}");
DBObject sort = (DBObject) JSON.parse("{'$sort': {'z':-1}}");
        
AggregationOutput output = mongoTemplate.getCollection("events2").aggregate(group, project, match, sort);
Iterator<DBObject> it = output.results().iterator();
List<String> result = new ArrayList<String>();
EventType eventType = new EventType();
while (it.hasNext()) {
    DBObject db = it.next();
    Map<String, String> _id = (Map<String, String>) db.get("_id");
    String qzc = _id.get("qzc");
    String qzt = _id.get("qzt");
    Integer z = (Integer) db.get("z");
    String type = eventType.get(qzt);
    result.add(qzc+" "+type+" "+z);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文