多个2dsphere索引,不确定要运行哪个geoNear

时间:2019-06-12 12:35:36

标签: node.js mongodb mongoose

我在MongoDB的聚合中使用$geoNearnear。我已将MongoDB数据库托管到mlabs 。并且在我的本地计算机上一切正常,但是不知道为什么当我部署我的应用程序时,我会遇到以下错误:

  
    

“ geoNear命令失败:{ok:0.0,errmsg:\”多个2dsphere索引,不确定在哪个geoNear上运行

  

下面是我使用的代码:

Shops.aggregate([
  {
     $geoNear: {
         near: { 
            type: "Point",
            coordinates: coordinates
         },
         distanceField: "dist.calculated",
         maxDistance: 80467,
         spherical: true
     }
  }
])
.then((products)=>{
      res.json(products);
})

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

如错误消息所示,这是因为您有多个2dsphere索引,所以$geoNear不知道要使用哪个索引。

在这种情况下,您可以:

  

如果您的集合具有多个2d和/或多个2dsphere索引,则必须使用key选项指定要使用的索引字段路径。指定要使用的地理空间索引提供了完整的示例。

文档中也提到了错误:

  

如果存在多个2d索引或多个2dsphere索引,而您未指定键,则MongoDB将返回错误。

您可以使用db.collection.getIndexes()列出集合中定义的所有索引。

下面是使用key参数的示例:

> db.test.insert([
  {_id:0, loc1:{type:'Point',coordinates:[1,1]}, loc2:{type:'Point',coordinates:[2,2]}},
  {_id:1, loc1:{type:'Point',coordinates:[2,2]}, loc2:{type:'Point',coordinates:[1,1]}}
])

然后我创建两个2dsphere索引:

> db.test.createIndex({loc1:'2dsphere'})
> db.test.createIndex({loc2:'2dsphere'})

运行$geoNear而不指定key将输出错误:

> db.test.aggregate({$geoNear:{near:{type:'Point',coordinates:[0,0]},distanceField:'d'}})
...
  "errmsg": "more than one 2dsphere index, not sure which to run geoNear on",
...

使用key: loc1将根据loc1索引对结果进行排序(_id: 0_id: 1之前):

> db.test.aggregate(
    {$geoNear: {
        near: {type: 'Point',coordinates: [0,0]},
        distanceField: 'd',
        key: 'loc1'}})
{ "_id": 0, "loc1": { "type": "Point", "coordinates": [ 1, 1 ] }, "loc2": { "type": "Point", "coordinates": [ 2, 2 ] }, "d": 157424.6238723255 }
{ "_id": 1, "loc1": { "type": "Point", "coordinates": [ 2, 2 ] }, "loc2": { "type": "Point", "coordinates": [ 1, 1 ] }, "d": 314825.2636028646 }

然后,使用key: loc2将根据loc2索引对结果进行排序(_id: 1_id: 0之前):

> db.test.aggregate(
    {$geoNear: {
        near: {type: 'Point',coordinates: [0,0]},
        distanceField: 'd',
        key: 'loc2'}})
{ "_id": 1, "loc1": { "type": "Point", "coordinates": [ 2, 2 ] }, "loc2": { "type": "Point", "coordinates": [ 1, 1 ] }, "d": 157424.6238723255 }
{ "_id": 0, "loc1": { "type": "Point", "coordinates": [ 1, 1 ] }, "loc2": { "type": "Point", "coordinates": [ 2, 2 ] }, "d": 314825.2636028646 }
相关问题