我是Java新手。 我检查了几个有总使用量的例子。但仍然没有什么疑问。
db.employee.aggregate({$unwind: '$dp.fin.Record'},
{$match:{"dp.mon":"patch.metrics",'dp.fin.Record':{$exists:1}}},
{$group:{_id: '$dp.fin.Record', count:{$sum:1}}},
{$project:{count:'$count'}}, {$group:{_id:'Total
Count',total:{$sum:'$count'}}});
任何人都可以帮我写java等价物。 我怀疑我们如何通过多个匹配条件,如上所示。 我正在尝试如下
BasicDBObject unwind = new BasicDBObject("$unwind",
"$dp.fin.Record"); DBObject match = new BasicDBObject("$match", new
BasicDBObjectBuilder(""));
答案 0 :(得分:3)
如果你上面的查询是正确的。你可以在下面的代码处理。
//Forming Unwind parts
DBObject unwind = new BasicObject("$unwind","$dp.fin.record");
//Forming Match parts
DBObject match = new BasicObject();
match.put("dp.mon","patch.metrics")
match.put("dp.fin.Record", new BasicDBObject("$exists",1));
//Forming Group parts
DBObject group1 = new BasicDBObject();
group1.put("_id", '$dp.fin.Record');
group1.put("count", new BasicDBObject("$sum", 1));
//Forming Project parts
DBObject project = new BasicDBObject();
project.put("count", '$count');
//Forming Group parts
DBObject group2 = new BasicDBObject();
group2.put("_id", 'Total Count');
group2.put("total", new BasicDBObject('$sum', '$count'));
/**
* Executing aggregation
*/
AggregationOutput output = mongoOperations.getCollection("employee").aggregate(unwind,
new BasicDBObject("$match",match),
new BasicDBObject("$group",group1),
new BasicDBObject("$project",project),
new BasicDBObject("$group",group2));
希望这可以帮到你。
答案 1 :(得分:3)
我认为这会有所帮助:
DBObject unwind = new BasicDBObject("$unwind", "$dp.fin.Record");
DBObject match = BasicDBObjectBuilder.start().push("$match")
.add("dp.mon", "patch.metrics")
.push("dp.fin.Record").add("$exists", true).get();
DBObject group1 = BasicDBObjectBuilder.start().push("$group")
.add("_id", "$dp.fin.Record")
.push("count").add("$sum", 1).get();
DBObject project= BasicDBObjectBuilder.start().push("$project")
.add("count", "$count").get();
DBObject group2 = BasicDBObjectBuilder.start().push("$group")
.add("_id", "Total Count")
.push("total").add("$sum", "$count").get();
// Suppose collection has been prepared
AggregationOutput aggr = collection.aggregate(Arrays.asList(unwind, match, group1, project, group2));