MongoDB排序了地理边界框

Nic*_*ick 5 geospatial mongodb

使用MongoDB有一种方法可以执行边界查询(在一个框内)并从中心点对结果进行排序,并让它们返回距离计算.

我意识到做一个半径附近可以为我提供一个距离有序集但我希望我试图确定它是否可能在一个盒子而不是一个圆圈内.

Mar*_*arc 9

不幸的是,这与你描述的完全不可能.根据"地理空间索引"文档的"边界查询"部分:"查询中的$ [结果]不按距离排序" http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing- BoundsQueries

有一些可能的解决方法.

1)您可以在查询内执行$并让应用程序计算从框中心返回的每个点的距离.

2)您可以先执行$ within查询,将点保存在数组中,然后运行$ near查询并结合$ in [].

例如,

想象一个带有边界[0,0]和[8,8]的框:

> var box = [ [ 0, 0 ], [ 8, 8 ] ]
Run Code Online (Sandbox Code Playgroud)

还有一些要点:

> db.points.find()
{ "_id" : 1, "name" : "a", "loc" : [ 5, 4 ] }
{ "_id" : 2, "name" : "b", "loc" : [ 4, 2 ] }
{ "_id" : 3, "name" : "c", "loc" : [ 1, 4 ] }
{ "_id" : 4, "name" : "d", "loc" : [ 2, 7 ] }
{ "_id" : 5, "name" : "e", "loc" : [ 7, 7 ] }
{ "_id" : 6, "name" : "f", "loc" : [ 9, 4 ] }
Run Code Online (Sandbox Code Playgroud)

首先查询$ within,并保存返回的点:

> var c = db.points.find({loc:{$within:{"$box":box}}})
> var boxResults = []
> while(c.hasNext()){boxResults.push(c.next().loc)}
Run Code Online (Sandbox Code Playgroud)

然后将$ near查询与$ in查询结合使用:

> db.points.find({loc:{$near:[4,4], $in:boxResults}})
{ "_id" : 1, "name" : "a", "loc" : [ 5, 4 ] }
{ "_id" : 2, "name" : "b", "loc" : [ 4, 2 ] }
{ "_id" : 3, "name" : "c", "loc" : [ 1, 4 ] }
{ "_id" : 4, "name" : "d", "loc" : [ 2, 7 ] }
{ "_id" : 5, "name" : "e", "loc" : [ 7, 7 ] }
Run Code Online (Sandbox Code Playgroud)

上述解决方案取自Google网上论坛上提出的类似问题:groups.google.com/group/mongodb-user/browse_thread/thread/22d1f0995a628c84/1f2330694a7cf969

希望这将允许您执行您需要执行的操作.