subtraction in mongo query does not work?

丶灬走出姿态 提交于 2019-12-06 22:36:27

You need to make a slight modification to your $project object. You need to make use of the Object that was obtained on subtracting 1 from count, rather than using the previous value of count.

DBObject project = new BasicDBObject("_id", 0);
DBObject countAfterSubtraction = new BasicDBObject("$subtract", 
                                     new Object[] {"$count", 1});
DBObject value = new BasicDBObject("$divide", 
                            new Object[] {"$value",countAfterSubtraction});
project.put("value", value);
project.put("Date", "$_id");
stages.add(new BasicDBObject("$project", project));

The above code would work for groups that have records >= 2. If there is a single group with only one record, the count after subtraction would be zero, resulting in a divide by zero error.

So you could modify your code, to include a $cond, to check if the count after subtraction is 0, if it is, then default it to 1, else keep the subtracted value of count.

DBObject project = new BasicDBObject("_id", 0);
DBObject countAfterSubtraction = new BasicDBObject("$subtract", 
                                       new Object[] {"$count", 1});
DBObject eq  = new BasicDBObject("$eq",
                        new Object[]{countAfterSubtraction,0});
DBObject cond = new BasicDBObject("$cond",
                         new Object[]{eq,1,countAfterSubtraction});
DBObject value = new BasicDBObject("$divide", 
                                new Object[] {"$value",cond});
project.put("value", value);
project.put("Date", "$_id");
stages.add(new BasicDBObject("$project", project));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!