我是mongodb的新手,
我的数据集包含以下文档:
{
"_id" : ObjectId("546fca4bbadc0f7939048d76"),
"name" : "kami",
"time" : "20141105230100",
"entity" : [
1,
3,
4
],
"count" : 10
}
并想象其中有1000个,现在我想通过entityid对它们进行分组并返回计数的总和,例如在对它们进行分组之后我会有类似的东西:
(实体)1:100 2:1000 3:300
。 。
如果实体不是数组,我可以这样轻松地做到:
DBCollection coll = db.getCollection("test");
DBObject groupFields = new BasicDBObject("_id", "$entity");
groupFields.put("sum", new BasicDBObject("$sum", "$count"));
DBObject group = new BasicDBObject("$group", groupFields);
List<DBObject> pipeline = Arrays.asList( group);
AggregationOutput output = coll.aggregate(pipeline);
for (DBObject result : output.results()) {
System.out.println(result);
}
但是现在我可以将实体作为数组吗?有可能吗?
答案 0 :(得分:0)
使用此:
DBCollection coll = db.getCollection("test");
DBObject unwind = new BasicDBObject("$unwind", "$entity");
DBObject groupFields = new BasicDBObject("_id", "$entity");
groupFields.put("sum", new BasicDBObject("$sum", "$count"));
DBObject group = new BasicDBObject("$group", groupFields);