MongoDB geoNear不返回任何结果
我有一个地理空间集合,我正在尝试查询给定范围内的结果。执行此操作时,我无法理解为什么查询返回的结果数组中没有任何信息。我尝试过不同的运行方法,但总是得到相同的结果。我需要知道我做错了什么,并且找不到任何理由来解释为什么这不应该起作用 以下是集合中文档的格式:MongoDB geoNear不返回任何结果,mongodb,geospatial,mongodb-query,Mongodb,Geospatial,Mongodb Query,我有一个地理空间集合,我正在尝试查询给定范围内的结果。执行此操作时,我无法理解为什么查询返回的结果数组中没有任何信息。我尝试过不同的运行方法,但总是得到相同的结果。我需要知道我做错了什么,并且找不到任何理由来解释为什么这不应该起作用 以下是集合中文档的格式: { "_id" : ObjectId("54432bd85ae1e944d857659d"), "FEATURE_ID" : 406, "Location" : { "properties" : { "name" :
{
"_id" : ObjectId("54432bd85ae1e944d857659d"),
"FEATURE_ID" : 406,
"Location" : {
"properties" : {
"name" : "Cement Trough Canyon",
"mapName" : "Blue House Mountain",
"class" : "Valley",
"state" : "AZ",
"county" : "Navajo",
"retrieved" : false
},
"geometry" : {
"type" : "Point",
"coordinates" : [
-110.5126118,
33.9950482
]
}
}
}
{
"geometry" : "2dsphere"
}
以下是我正在尝试运行的查询:
db.runCommand({
geoNear: "gis",
near: { type: "Point",
coordinates: [ -110.512612, 33.995048 ] },
spherical: true
})
以下是我为集合创建的索引:
{
"_id" : ObjectId("54432bd85ae1e944d857659d"),
"FEATURE_ID" : 406,
"Location" : {
"properties" : {
"name" : "Cement Trough Canyon",
"mapName" : "Blue House Mountain",
"class" : "Valley",
"state" : "AZ",
"county" : "Navajo",
"retrieved" : false
},
"geometry" : {
"type" : "Point",
"coordinates" : [
-110.5126118,
33.9950482
]
}
}
}
{
"geometry" : "2dsphere"
}
结果如下:
{
"results" : [],
"stats" : {
"nscanned" : NumberLong(26),
"objectsLoaded" : NumberLong(26),
"avgDistance" : NaN,
"maxDistance" : 0,
"time" : 4
},
"ok" : 1
}
根据这一点,查询可以正常运行,但不会从集合中的对象中提取任何数据。我能做些什么来解决这个问题吗
谢谢大家! 问题在于,您将几何体作为位置的子字段,因此当您运行
db.gis.ensureIndex({"Location": "2dsphere"});
MongoDB在位置上创建索引,就好像这是几何体字段的名称一样,即使该字段不存在,并返回OK(在我看来,这有点令人困惑)。要进一步说明此问题,请尝试以下方法:
db.gis.ensureIndex({"i_do_not_exist": "2dsphere"});
这将返回如下内容,具体取决于您已有的索引数量:
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}
解决方案是使用点符号来引用嵌入的几何字段,即
db.gis.ensureIndex({"Location.geometry": "2dphere"});
然后您的查询将返回一个结果。有关更多信息,请参阅文档中的部分
或者,可以重新构造文档,使“几何体”字段处于顶层
db.gis.insert({
"_id" : ObjectId("54432bd85ae1e944d857659d"),
"FEATURE_ID" : 406,
"Location" : {
"properties" : {
"name" : "Cement Trough Canyon",
"mapName" : "Blue House Mountain",
"class" : "Valley",
"state" : "AZ",
"county" : "Navajo",
"retrieved" : false
}
},
"geometry" : {
"type" : "Point",
"coordinates" : [
-110.5126118,
33.9950482
]
}
});
db.gis.ensureIndex({"geometry": "2dsphere"});
db.runCommand({
geoNear: "gis",
near: { type: "Point",
coordinates: [ -110.512612, 33.995048 ] },
spherical: true
});
现在返回上面的记录