是找出整个表 a大于b的总数量,要怎么操作数据库呢,那就要用到$subtract函数

MongoDB比较两列大小 使用$subtract函数,

 // MongoDB 比较两列大小求出  啊>b 的数值

  db.seoProduceAnalyse.aggregate([
{
"$project":{
"val":{"$subtract":["$a","$b"]} // a与 b两个值减 得到值 val
}
},
{
"$match":{
"val":{"$lt":1} // 条件 where 是 val《1
}
},
{
"$group":{
"_id":1, // id
"count":{"$sum":1} // 展示 count 值为 总数
}
}
])

结果:

MongoDB比较两列大小 使用$subtract函数-LMLPHP

java 中代码

//         $group
DBObject group = new BasicDBObject();
DBObject q = new BasicDBObject();
DBObject l = new BasicDBObject();
DBObject c = new BasicDBObject();
c.put("$sum" ,1);
q.put("_id" ,1);
q.put("count",c );
group.put("$group", q); // $project
DBObject project = new BasicDBObject();
DBObject p = new BasicDBObject();
DBObject sb = new BasicDBObject();
BasicDBList list = new BasicDBList();
list.add("$a");
list.add("$b");
sb.put("$subtract",list);         // 使用$subtarct函数
p.put("val", sb);
project.put("$project", p); // $match
DBObject match = new BasicDBObject();
DBObject qm = new BasicDBObject();
DBObject qmc = new BasicDBObject();
qmc.put("$lt", Integer.valueOf("0"));
qm.put("val", qmc);
match.put("$match",qm);
AggregationOutput output = collection.aggregate(project,match,group); // 顺序必须是 project match group
05-08 08:23