我有一个包含多边形的json,这些多边形代表一个国家/地区所有城市的分隔符(总共78个)。例如:
{
"City1":[
[-67.103276,18.513426],
[-67.10339411502086,18.514532657212502],
[-67.093752,18.515757],
[-67.05297606966441,18.512073045833525]
],
"City2":[
[-67.16901339052771,18.472154288860388],
[-67.169016,18.478488],
[-67.138249,18.507776],
[-67.12906260088943,18.510642646697203],
[-67.125655,18.511706]
],
"City3":[
[-66.034932,18.333452],
[-66.03494,18.332214],
[-66.035911,18.328084],
[-66.035731,18.31961],
[-66.036859,18.318627]
],
...
}
我正在使用MongoDB的ruby驱动程序。该数据库包含一组点(索引为2dsphere)。我需要计算一个城市内的总点数。结果应该说,例如," City1包含56个点,City2包含40个点,City3包含100个点"。
这是我用来查找单个多边形内的点,并设置日期范围from_date到end_date的代码(因为这些点具有日期属性)
polygon = [[-67.103276,18.513426],[-67.10339411502086,18.514532657212502],[-67.093752,18.515757],[-67.05297606966441,18.512073045833525]]
from_date = DateTime.strptime(params[:from_date], '%Y-%m-%d')
from_date = Time.utc(from_date.year, from_date.month, from_date.day)
to_date = DateTime.strptime(params[:to_date], '%Y-%m-%d')
to_date = Time.utc(to_date.year, to_date.month, to_date.day)
@coll = db.collection("points")
recordset = @coll.find(
{
"$and" => [
{ "geometry.coordinates" => {
"$within" => {"$polygon" => polygon}
}},
{ "properties.time" => {
:$gte => from_date,
:$lte => to_date
}}
]
},
:fields => { :_id => false }
)
有什么方法可以用一个查询对所有城市的结果进行分组,或者我必须查询数据库78次以获得每个城市的计数?