示例日期(集合名称'人员')
{"person" : "Frank",
"coords" : [
{
"point":new GLatLng(40.266044,-74.718479),
},
{
"point":new GLatLng(40.211600,-74.695702),
}
] }
{"person : ""Bob",
"coords" : [
{
"point":new GLatLng(40.266044,-74.718479),
},
{
"point":new GLatLng(40.211600,-74.695702),
},
{
"point":new GLatLng(40.294535,-74.682012),
}
] }
目标:获得' coord'的总数。每个人文件的条目(总体累计)
预期结果5
我尝试了什么
public int getTotalCoordinateCount(){
BasicDbObject project= new BasicDBObject()
.append("count",new BasicDBObject("$size","coords"))
AggregationOutput output = db.getPeopleCollection().aggregate(Arrays. <DBObject>asList(
new BasicDBObject("$project", project);
BasicDbObject result = (BasicDBObject)output.results().iterator.next();
return result.getInt("count");
}
问题我得到:2
对我在mongo聚合框架中做错的事情一无所知。我怀疑我需要包含$sum
,但不确定
答案 0 :(得分:1)
您需要在聚合管道中的coords
字段上执行展开操作。之后,您按Null
并使用count
字段进行分组,以计算结果集,您将获得所有文档中所有数组的元素总数。
答案 1 :(得分:1)
public int getTotalCoordinateCount(){
BasicDbObject group = new BasicDBObject()
.append("_id", 1)
.append("count", new BasicDBObject("$sum", 1));
BasicDbObject project= new BasicDBObject()
.append("_id", 0)
.append("count", 1);
AggregationOutput output = db.getPeopleCollection().aggregate(Arrays. <DBObject>asList(
new BasicDBObject("$unwind", "coords"),
new BasicDBObject("$group", group),
new BasicDBObject("$project", project)
);
BasicDbObject result = (BasicDBObject)output.results().iterator.next();
return result.getInt("count");
}