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

新手上路,请多包涵

在使用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);

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

阅读 7.6k
1 个回答
✓ 已被采纳新手上路,请多包涵

很抱歉现在才来补充回答,此问题早已找到答案,就是用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);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进