MongoDB地理空间索引,如何与数组元素一起使用?

我想让凯文酒吧点附近的特定位置。 这里是userSpots集合:

{ 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 在这里描述)。

索引创build使用:

 db.userSpots.ensureIndex({"location": "2dsphere"}) 

在我的聚合pipe道,我find匹配使用:

 {"$match":{"location":{"$geoWithin": {"$centerSphere":[[location.coordinates[0], location.coordinates[1]], radius/3959]}}}} 

(其中半径以英里为单位进行测量 – 幻数用于转换为弧度)。

索引包含地理数据数组的文档MongoDB使用多键索引。 索引之前,多键索引将文档展开为具有单个值的某些文档而不是数组。 所以这个索引把这个关键字段看作是单个值字段而不是数组。

尝试查询它没有$ elemMatch运算符。