示例日期(集合名称“people”)
{"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),
}
] }
目标:获取每个人文档的“坐标”条目总数(总体累计)
预期结果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
但不确定在哪里
最佳答案
您需要在聚合管道中对coords
字段执行展开操作。之后,您使用 count
字段对 Null
进行分组,以对结果集进行计数,您将获得所有文档中所有数组的元素总数。
关于java - 蒙戈 : count number of array elements for each entry in collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33133526/