mongodb - spring-data-mongo aggregate 筛选两个字段相等
本文介绍了mongodb - 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);
请问各位是哪里有错吗,或者,有什么方法能比较一下两个字段是否相等吗?拜谢~
解决方案
很抱歉现在才来补充回答,此问题早已找到答案,就是用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);
}
这篇关于mongodb - spring-data-mongo aggregate 筛选两个字段相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文