我想在给定位置附近找到凯文酒吧。这是用户斑点集合:
{ user:'Kevin',
spots:[
{ name:'a',
type:'pub',
location:[x,y]
},
{ name:'b',
type:'gym',
location:[v,w]
}
]
},
{ user:'Layla',
spots:[
...
]
}
这是我尝试过的:
db.userSpots.findOne(
{ user: 'Kevin',
spots: {
$elemMatch: {
location:{ $nearSphere: [lng,lat], $maxDistance: d},
type: 'pub'
}
}
},
},
function(err){...}
)
我收到一个奇怪的错误。Mongo告诉我位置字段中没有索引:2d。但是当我检查db.userSpots.getIndexes()时,2d索引就在那里。为什么Mongodb看不到索引?我做错了什么吗?
MongoError: can't find special index: 2d for : { spots: { $elemMatch: { type:'pub',location:{ $nearSphere: [lng,lat], $maxDistance: d}}}, user:'Kevin'}
db.userSpots.getIndexes() 输出 :
{
"0" : {
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "mydb.userSpots",
"name" : "_id_"
},
"1" : {
"v" : 1,
"key" : {
"spots.location" : "2d"
},
"ns" : "mydb.usersBoxes",
"name" : "spots.location_2d",
"background" : true,
"safe" : null
}
}
对于类似的地理空间应用程序,我将位置转换为 GeoJSON:
{
"_id" : ObjectId("5252cbdd9520b8b18ee4b1c3"),
"name" : "Seattle - Downtown",
"location" : {
"type" : "Point",
"coordinates" : [
-122.33145,
47.60789
]
}
}
(坐标为经度/纬度格式。Mongo对GeoJSON的使用在这里描述。
索引是使用以下方法创建的:
db.userSpots.ensureIndex({"location": "2dsphere"})
在我的聚合管道中,我使用以下方法查找匹配项:
{"$match":{"location":{"$geoWithin": {"$centerSphere":[[location.coordinates[0], location.coordinates[1]], radius/3959]}}}}
(其中半径以英里为单位 - 幻数用于转换为弧度)。
要索引包含地理数据数组的文档,MongoDB使用多键索引。多键索引在索引之前将文档展开为一些具有单个值而不是数组的文档。因此,索引将该键字段视为单值字段而不是数组。
尝试在没有运算符的情况下查询它$elemMatch。